node.js - 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在哪里?
解决方案
这是因为您在处理所有 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!`));
推荐阅读
- javascript - 将 div 对齐在一行并固定在底部
- c++ - 在函数中获取原始类型的指针
- json - 如何从 Get Response Body - Robot 框架中获取值
- dll - 构建新项目包括 dll 和编译器
- ios - 当第一个视图控制器在 iOS 中隐藏其导航栏时,向后滑动会导致导航栏立即隐藏(不顺畅)
- ios - 切换设备时布局中断
- javascript - 如何避免 NaN 并在 OOP Javascript 上添加和减去
- r - 如何在整个列中保留字符串中的特定单词并删除所有其余单词?
- r - 从 R 中的 data.frame 中排除值
- mongodb - $setEquals 与列表列表