javascript提取从未到达nodejs服务器上的POST请求

我正在尝试使用获取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请求收到此错误:

javascript提取从未到达nodejs服务器上的POST请求

先谢谢您了:)

puenshou 回答:javascript提取从未到达nodejs服务器上的POST请求

我解决了这个问题。我没有正确处理传入的请求,因为我不知道fetch在发送实际的POST请求之前会发送带有OPTION方法的预检请求。因此,我通过在我的索引文件中的所有其他请求之上添加了此行来解决此问题,该请求将在每次发出请求(使用任何方法)时执行。

app.use(function (req,res,next) {

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");
res.header("Access-Control-Allow-Methods"," GET,POST,PUT,PATCH,DELETE,OPTIONS");

next();
});
本文链接:https://www.f2er.com/2998497.html

大家都在问