简体   繁体   English

Node.js/http express post 方法失败,出现 404

[英]Node.js/http express post method failed with 404

I used node.js express to create an api server.我使用 node.js express 创建了一个 api 服务器。 However the post method failed.但是 post 方法失败了。 I bevelieve It's my fault since it's very simple, but I can't pick it out.我相信这是我的错,因为它很简单,但我无法挑选出来。 Any help would be appreciated.任何帮助,将不胜感激。 The following is the code:以下是代码:

var express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.json({
        message: err.message,
        error: err
    });
});
app.post('/chat', (req, res) => {
    const data = req.body.data;
    console.log('/chat---------------', data);
    res.status(200).send();
});
app.listen(3000, () => console.log(`Chat app listening!`));

And I tested the api with curl as the following:我用 curl 测试了 api,如下所示:

curl -X POST http://localhost:3000/chat -H "Content-Type: application/json" -d '{"abc":"cde"}'

And the result displayed as 404. Where is the bug?结果显示为404。bug在哪里?

It's because you added the middleware for 404 before your endpoint, which handles all API calls.这是因为您在端点之前添加了 404 的中间件,它处理所有 API 调用。

Here is the correct order.这是正确的顺序。

var express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));


app.post('/chat', (req, res) => {
    const data = req.body.data;
    console.log('/chat---------------', data);
    res.status(200).send();
});

app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.json({
      message: err.message,
      error: err
  });
});

app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.listen(3000, () => console.log(`Chat app listening!`));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM