简体   繁体   中英

Handling Http requests

I'm very much new to backend development and integrating front end to the backend. My issue is that while trying to send a post request I get a 404 status code POST http://localhost:5000/api/data 404 (Not Found) The code on my front end is:

useEffect(() => {
    fetch('http://localhost:5000/api/data')
    .then(res => { return res.json() })
    .then((data) => {
      setData(data)
      setDatarecieved(true)
    })
  }, [])


  const clickHandler = () => {
    fetch('http://localhost:5000/api/data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          "id": 5,
          "name":"test"
        })
      })
    }

Note that the first part of it where works flawlessly. My issue is limited to the post req.

The code in my back end goes as follows:

const express=require('express');
const app=express();
const data = require('./data.json');

const cors=require("cors");
const corsOptions ={
   origin:'*',
   credentials:true,
   optionSuccessStatus:200,
}

app.use(cors(corsOptions)) 

app.get('/',(req,res)=>{
    res.send('Hello World');
});

app.get('/api/data',(req,res)=>{
    res.send(data);
});

app.get('/api/data/:id',(req,res)=>{
    const x=data[req.params.id];
    res.send(data);
});

app.listen(5000,()=>{
    console.log('Server is running on port 5000');
});

Thanks in advance

Boss it looks like your looking for this

 app.post('/api/data',(req,res)=>{
    console.log(req.body)
        res.send(req.body);
    });

您的后端没有 post 方法的路线

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