【发布时间】:2025-12-16 02:15:02
【问题描述】:
我使用 express-generator 来生成一个 express 应用的基本结构。
我在 routes/my.js 中有这个:
router.use('/update', function(req, res, next) {
req.headers['content-type'] = 'application/json';
console.log('router use invoked');
next();
});
router.get('/update', function(req, res, next) {
console.log('=== GET /my/update', req.body);
});
router.post('/update', function(req, res, next) {
console.log('=== POST /my/update', req.body);
});
我在 app.js 中添加了:
var my = require('./routes/my');
app.use('/', routes);
app.use('/users', users);
app.use('/my', my);
GET 工作正常,路由器中间件实际工作(调用了 console.log),但标头未设置为 app/json(因为 post 中的日志消息输出正文为空)。
我可以通过在任何其他中间件之前添加这个来解决这个问题
app.use('/my/update', function(req, res, next) {
req.headers['content-type'] = 'application/json';
next()
});
而且它有效。我尝试在任何其他中间件之前移动 app.use('my', my); 行,但它完全停止工作。
为了优先使用我的 router.use,我该怎么做?
【问题讨论】:
标签: javascript node.js express