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
CodePudding user response:
Boss it looks like your looking for this
app.post('/api/data',(req,res)=>{
console.log(req.body)
res.send(req.body);
});
CodePudding user response:
you don't have a route for post method in your backend