首页 > 解决方案 > 使用 axios 响应原生 api 调用

问题描述

我有 nodeJs 后端,我在其中创建了这个 api

app.post("/addInvoice", (req, res) => {
  let invoice = req.body;
  var sql =
    "INSERT INTO invoice (address, email, billnumber, price, status) VALUES(?, ?, ?, ?, 'sent');";
  mysqlConnection.query(
    sql,
    [
      invoice.address,
      invoice.customeremail,
      invoice.billnumber,
      invoice.totalprice,
    ],
    (err, rows, fields) => {
      if (!err) {
        res.send(rows);
      } else {
        res.send(err);
      }
    }
  );
});

当我使用邮递员调用此 API 时,它运行良好。

但现在我需要在我的 react-native 应用程序中通过 buttonclick 调用它。

axios
      .post("http://localhost:3000/addInvoice", {
        address: address,
        customeremail: email,
        billnumber: invoicenumber,
        totalprice: totalPrice,
      })
      .then((response) => {
        alert(response);
      });

当我发送这个并且警报(响应)什么都不返回时,我什么也没有发生。

可能是什么问题呢?

标签: node.jsreactjsreact-nativeaxios

解决方案


您的模拟器(或电话)是一个独立的设备,与您的网络浏览器、邮递员或服务器不在同一 IP(本地主机或 127.0.0.1)上运行。

为了从您的模拟器(或电话)向您的服务器发出请求,您需要通过您的计算机 IP 地址访问您的服务器:在 Windows 上,通过在命令提示符下运行 ipconfig 获取您的 IP 地址,或者在这里:系统偏好设置 > 网络 >高级 > TCP/IP > IPv4 地址。

而不是 http://localhost:port 你应该使用 http://your_ip_address:port


推荐阅读