【问题标题】:React cannot fetch data from ExpressReact 无法从 Express 获取数据
【发布时间】:2021-11-27 18:43:36
【问题描述】:

我正在学习 ReactExpress,据说我正在开发我的学习应用程序,它只从 MySQL 获取数据,然后将其可视化。

所以,我用路由器做了一个简单的快递服务器:

//controllers.js
const getData = async (SQL) => {
  try {
    const data = await new Promise((resolve, reject) => {
      pool.query(SQL, (err, res) => {
        if (err) reject(err);
        else resolve(res);
      });
    });
    return data;
  } catch (err) {
    return err;
  }
};

//router.js 
router.get("/CB/fridge01", (req, res, next) => {
  let sql = "SELECT * FROM fridge01";
  getData(sql)
    .then((result) => res.json(result))
    .catch((err) => res.json(err));
});

//index.js
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use("/api", router);

app.get("/", (req, res) => {
  res.redirect("localhost:" + port + "/api/CB/fridge01");
});


app.listen(port, (error) => {
  error
    ? console.log(`An error occurred: ${error}`)
    : console.log(`The server has started at http://localhost:${port}`);
});

然后在我的 react 组件中,我只使用 ComponentDidMount 来执行 fecth api:

componentDidMount() {
     //192.168.88.169 is my local IP and port 8080 is setup in index.js
    fetch("192.168.88.169:8080/api/CB/fridge01", { method: "GET" })
      .then((res) => {
        res
          .json()
          .then((json) => {
            this.setState({ metrics: json });
          })
          .catch((err) => console.log(err));
      })
      .catch((err) => console.log(err));
}

它给我一个控制台错误:SyntaxError: Unexpected token < in JSON at position 0

当我用curlpostman 甚至浏览器打开我的快递时,我得到相同的数据:

[{"id":1,"recorded":"2021-11-22T11:16:22.000Z"}] 

这些只是我硬编码到数据库表中的示例数据

感谢您的帮助和耐心,请原谅我的语法水平。

【问题讨论】:

  • 在浏览器中,打开控制台/检查器(F12 / Ctrl + Shift + I / 检查这个),转到“网络”选项卡并检查响应。您很可能缺少其中一个标题。顺便说一句:你为​​什么要去then() 而你正在接近回调地狱。使用链.then(reap=>resp.json()).then(json=> {this.setState({ metrics: json })} ).catch(/*only one*/)
  • 我通过犯这样的错误来学习东西,以前从未使用过 Promises async/await。所以,我打开了控制台的network 部分,猜猜我发现了什么,URL fetch 是从以下位置获取数据的:http://localhost:3000/192.168.88.169:8080/api/CB/fridge01 这是总的bullsh * t 我通过在请求的IP fetch(http://....) 前面输入协议来解决这个问题.现在我收到 Cors 错误(我通过使用:res.header("Access-Control-Allow-Origin", "*"); 解决了这个问题)。它现在工作,谢谢。无论如何,我该如何结束这个问题?

标签: javascript mysql reactjs express


【解决方案1】:

fetch API 在反应端存在问题。我没有从192.168.88.169:8080/... 获取数据,而是从localhost:3000/192.168... 获取数据

为了解决这个问题,我将http 协议放入获取 URL 中。 (fetch("http://192..."))

然后我简单地允许了 CORS,瞧!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-11
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多