I used express-generator to generate the basic structure of an express app.
I have this in 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:
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).
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); line before any other middle-ware but it stopped working altogether.
What can I do in order to give priority to my router.use?
You're adding the header to the request object, not the response. 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.
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.
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 :
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(). You don't need to set application/json headers if you use res.json().