【问题标题】:Get 404 error When trying to fetch data from Node.js in React.js While server is running在服务器运行时尝试从 React.js 中的 Node.js 获取数据时出现 404 错误
【发布时间】:2023-01-09 10:53:17
【问题描述】:

对后端不熟悉,第一次尝试。 Techset 是 React.js、Node.js、express.js 和 mysql。 我想请求查询结果,但出现 404 错误。 这是代码。

在 React.js 中

    const resident_name = 'sss';
    let rates = [];

    async function getData(){
        const res = await fetch('http://localhost:3001', {
            method: 'POST',
            mode: 'cors',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({name: {resident_name}}),
        });
        rates = await res.result;
    };
    getData();

我想在包含它的页面出现后立即执行该功能。

在 Node.js 中

app.post("/", (req,res)=>{
  res.set('Content-Type', 'application/json');
  console.log("i got "+req.body.name);

  db.query(`SELECT r.* 
    FROM rate r INNER JOIN resident rs on r.resident_id = rs.resident_id 
    WHERE rs.name = ${req.body.name}`, (err,result)=>{
      // result is an array that contains dictionaries.
      if(err) throw err;

      result.forEach(r => {
        console.log(r)
      });

      res.send(result)
  });
});

我不确定是什么导致了错误。如果你们知道一些相关信息,我可以得到解决方案吗? 谢谢!

我尝试将 post 方法更改为 get 方法并确保服务器地址正确。

【问题讨论】:

    标签: javascript node.js reactjs express


    【解决方案1】:

    404 错误只有在提到的地址没有任何监听时才会发生:port

    确保您使用正确的端口号请求正确的 url,您的 express 应用程序在该端口号中运行。

    Express 应用程序默认使用端口 3000

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 2016-11-23
      相关资源
      最近更新 更多