处理HTTP请求
我对后端开发和将前端整合到后端非常陌生。我的问题是,在尝试发送邮政请求时,我会得到404状态代码发布http:// localhost:5000/api/data 404(找不到)
我的前端的代码是:
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"
})
})
}
请注意,其中的第一部分可完美地工作。我的问题仅限于帖子。
我后端的代码如下:
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');
});
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的后端没有邮政方法的路线
you don't have a route for post method in your backend
老板看来你在寻找这个
Boss it looks like your looking for this