我正在尝试使用获取API将一些数据发布到我的nodejs服务器,但似乎获取请求从未到达我的服务器。
获取代码
const resp = await fetch("http://localhost:5000/api/students/", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: `{ "name": "Ahmed", "seat": 4 }` }); console.log(resp); const json = await resp.json(); return json;
nodeJS帖子正文
route.post("/", CORS, async (req, res) => { console.log('abc', req.body); const { error } = validateStudent(req.body); if (error) return res.status(400).send(error.details[0].message); const result = await addStudent(req.body); if (!result) return res.status(400).send("Student cannot be added"); res.status(200).send(result); });
CORS中间件代码
console.log('avcx'); res.header("Access-Control-Allow-Origin", "*").header( "Access-Control-Allow-Credentials", true); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); console.log('acvced'); next();
您可以看到我已经在服务器上完成了一些日志,但是什么也没显示... BTW传送在获取请求时工作正常。
与邮递员发送相同的请求效果很好。
我不知道为什么会收到此错误,我通过创建中间件'CORS'来解决GET请求的此错误,但对于POST请求我仍然遇到此错误:-
预先感谢:)
[我正在尝试使用获取API将一些数据发布到我的nodejs服务器,但似乎获取请求从未到达我的服务器。获取代码const resp = await fetch(“ http:// localhost:5000 / api / students /” ,{...
我解决了这个问题。我没有正确处理传入的请求,因为我不知道fetch在发送实际的POST请求之前会发送带有OPTION方法的预检请求