Reputation: 4234
I have a middleware doing some auth. In this auth-method I need to set a response header.
server.get('/api/users, auth(), getUsers);
My authmethod:
module.exports = (isProduction) => {
return function(req, res, next){
...
next();
}
}
How do I attach a header in this auth function?
Upvotes: 9
Views: 18647
Reputation: 533
How you actually use it as middleware.
app.use(function (req, res, next) {
res.setHeader('access-control-allow-origin', '*');
next()
})
Upvotes: 4
Reputation: 1731
This is not a node.js
core question but rather a question on express.js
.
In that case your reference is: http://expressjs.com/en/4x/api.html#res.set
The set() function's signature is: res.set(field [, value])
The res
object is a wrapper around node's native http.response
api.
You can call .set()
multiple times in express.js middleware as long as they occur before the next()
function is invoked, which calls the following middleware in the chain.
There is nothing special about next(). But if the following middleware writes the headers, by calling res.send() or even res.redirect(), then one can no longer set the headers.
You can call set multiple times, and you can use an object to pass multiple headers, as in the documentation example:
res.set('Content-Type', 'text/plain');
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
});
Upvotes: 2
Reputation: 11969
I assume you are using express.js
. In express, there is a set
function (documentation here. You can use it like this
res.set('<header name>', '<header value>')
before calling next()
Upvotes: 13