[英]Node.js/http express post method failed with 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在哪里?
这是因为您在端点之前添加了 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!`));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.