【问题标题】:Node.js/http express post method failed with 404Node.js/http express post 方法失败,出现 404
【发布时间】:2021-06-04 21:02:40
【问题描述】:

我使用 node.js express 创建了一个 api 服务器。但是 post 方法失败了。我相信这是我的错,因为它很简单,但我无法挑选出来。任何帮助,将不胜感激。 以下是代码:

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!`));

我用 curl 测试了 api,如下所示:

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

结果显示为404,bug在哪里?

【问题讨论】:

  • 中间件顺序很重要,您的设置 404 顶部有一个全部内容

标签: node.js express


【解决方案1】:

这是因为您在端点之前添加了 404 的中间件,它处理所有 API 调用。

这是正确的顺序。

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!`));

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 2022-09-30
    • 2017-05-16
    • 2014-07-21
    • 2018-05-21
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多