Express router.use not working
Express router.use not working
我使用express生成器生成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);
行,但它完全停止了工作。
我可以做些什么来优先考虑我的路由器。use?
您将头添加到request
对象,而不是响应。此外,以下是首选的方法。
router.use('/update', function(req, res, next) {
res.header('content-type', 'application/json');
console.log('router use invoked');
next();
});
ExpressJS就是关于使用中间件的。
根据这里的官方文档,中间件是一个可以访问请求对象(req)、响应对象(res)和Express应用程序请求-响应周期中的下一个中间件的函数,通常由名为next的变量表示。
中间件可以:
- 执行任何代码
- 更改请求和响应对象
- 结束请求-响应周期
- 调用堆栈中的下一个中间件
我想指出一些关于你的my.js路由器的事情,如果你不想发回任何响应,那么它应该是这样的:
router.get('/update', function(req, res, next) {
res.end();
});
router.post('/update', function(req, res, next) {
res.end();
});
您必须结束您的请求和响应周期,否则它将被挂起。实际上,您希望将一些数据(最好是JSON数据)发送回客户端,这样您就可以使用res.JSON()或res.send()。如果您使用res.jsn(),则不需要设置application/JSON头。
相关文章:
- $rootScope not working
- jQuery document.ready not working
- Javascript getElementsByTagName not working?
- JQuery.val( ) not working
- Tomcat websocket is not working
- Javascript JSON.parse not working
- NodeJS Multer is not working
- Regex not working
- Ember run.debounce not working
- AngularJs 1 not working
- document.getElementById.style.backgroundImage not working
- Rxjs5, distinct() is not working
- createOscillator noteOn not working
- Javascript - .getHours() not working
- Javascript setTimeout not working | onkeydown
- MongoDB $pull not working
- Express router.use not working
- JSONP not working
- window.opener not working in chrome & IE
- Backbone + RequireJS: Collection.each() is not working