javascript 获取永远不会到达 nodejs 服务器上的 POST 请求

javascript fetch never reaches the POST request on nodejs server

我正在尝试 post 使用 fetch api 将一些数据发送到我的 nodejs 服务器,但似乎 fetch 请求从未到达我的服务器..

获取代码

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 post 正文

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();

如您所见,我已经在我的服务器上完成了一些日志记录,但没有显示任何内容...顺便说一句,对于 get 请求,一切都正常工作。

用 postman 发送相同的请求工作正常。

我不知道为什么会收到此错误 我通过创建中间件 'CORS' 解决了 GET 请求的此错误,但我仍然收到 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, POST, DELETE, OPTIONS");

next();
});