简体   繁体   中英

Get 404 error When trying to fetch data from Node.js in React.js While server is running

I am not familiar with back-end and it is the first time to try it out. Techset is React.js, Node.js, express.js, and mysql. I want to request result of a query but 404 error occurs. This is the code.

In 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();

I want to execute the function as soon as the page that has it shows up.

In 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)
  });
});

I am not sure what causes the error. Can I plz get solution if you guys know some info about it? Thank you!

  • Edited: I am running both React.js on port 3000 and Node.js on port 3001. Once I type node index.js, I can see Server is listening to 3001 message on server-side console with this code below.
app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

Result on the console: Server listening on 3001

I'm working on making sure the server is running in the way the first answer suggested.

  • first, make sure your server's API endpoint is correct and running.

  • For that, you can use Vs code extension like Thunder client by passing your port.

  • And check for any.network issue using ping command or firewall
    block.

  • Also, check your header request or use tool like curl . In
    react.js while request from server, CORS also block to make request
    on the browser (as i have face same issue on past). So, make sure you check the server logs.

404 error occurs only if there is nothing is listening in the mentioned address: port .

Make sure you are requesting to the correct url with correct port number in which your express app is running.

Express app defaults to port 3000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM