[英]Express router.use not working
I used express-generator to generate the basic structure of an express app. 我使用express-generator生成了Express应用程序的基本结构。
I have this in routes/my.js: 我在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);
});
And in app.js I added: 在app.js中,我添加了:
var my = require('./routes/my');
app.use('/', routes);
app.use('/users', users);
app.use('/my', my);
It's working fine for GET, and the router middle-ware is actually working (console.log is called), but the headers is not being set to app/json (as the log message in post outputs the body to be empty). 对于GET来说,它工作正常,并且路由器中间件实际上正在运行(调用了console.log),但是没有将标头设置为app / json(因为post中的日志消息将主体输出为空)。
I can solve this by adding this before any other middle-ware 我可以通过在其他任何中间件之前添加它来解决此问题
app.use('/my/update', function(req, res, next) {
req.headers['content-type'] = 'application/json';
next()
});
And it works. 而且有效。 I tried moving the app.use('my', my);
我尝试移动app.use('my', my);
line before any other middle-ware but it stopped working altogether. 在其他中间件之前排成一行,但它完全停止了工作。
What can I do in order to give priority to my router.use? 为了优先使用router.use我该怎么做?
You're adding the header to the request
object, not the response. 您正在将标头添加到request
对象,而不是响应。 Also the below is the preferred way to do it. 另外,下面是执行此操作的首选方法。
router.use('/update', function(req, res, next) {
res.header('content-type', 'application/json');
console.log('router use invoked');
next();
});
ExpressJS is all about working with middle wares. ExpressJS就是关于中间件的。
According to official documentation here , Middleware is a function with access to the request object ( req ), the response object ( res ), and the next middleware in line in the request-response cycle of an Express application, commonly denoted by a variable named next. 根据此处的官方文档,中间件是可以访问请求对象( req ),响应对象( res )和Express应用程序的请求-响应周期中的下一个中间件的函数,通常用名为的变量表示下一个。
Middleware can: 中间件可以:
I would like to point a few things about your my.js router, if you don't want to send any response back then it should be something like : 我想指出一些有关my.js路由器的信息,如果您不想发送回任何响应,则应该是这样的:
router.get('/update', function(req, res, next) {
res.end();
});
router.post('/update', function(req, res, next) {
res.end();
});
You must end your request, response cycle else it will be left hanging. 您必须结束您的请求,否则响应周期将被搁置。 Practically you would like to send some data(preferably JSON data) back to client so you can use res.json() or res.send() . 实际上,您希望将一些数据(最好是JSON数据)发送回客户端,以便可以使用res.json()或res.send() 。 You don't need to set application/json headers if you use res.json(). 如果使用res.json(),则无需设置application / json标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.