首页 > 解决方案 > Node.js/http express post 方法失败,出现 404

问题描述

我使用 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在哪里?

标签: node.jsexpress

解决方案


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

这是正确的顺序。

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

推荐阅读