[英]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:我的问题是,在尝试发送发布请求时,我得到一个 404 状态代码
POST http://localhost:5000/api/data 404 (Not Found)
我前端的代码是:
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.
我的问题仅限于 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 方法的路线
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.