Ben Diamant
Ben Diamant

Reputation: 6206

ExpressJS: Append header to incoming request object

I'm trying to append additional header to an incoming request, it can't seem to work.

server.get('/', function md1(req, res, next) {
    req.setHeader('px-test-header', 1234); // Error - "req.setHeader is not a function"
    req.headers['px-test-header'] = 1234; // nothing happens
 }, function (req, res, next) {
    console.log(req.get('px-test-header')); // always undefined
}, handler);

What am I doing wrong? Is it even possible?

Note - I do not want to modify the request object with additional parameter instead.

Upvotes: 3

Views: 9260

Answers (2)

Elkhan Shahverdi
Elkhan Shahverdi

Reputation: 26

You can set header before routing. Check this code

var router = express.Router();

router.use(function(req, res, next) {
   // set the header you wish to append
   req.headers('px-test-header', 1234);
   next();
});


router.get('/', function(req, res){
    console.log(req.headers)
});

Upvotes: -3

Vidur Khanna
Vidur Khanna

Reputation: 138

setHeader is a function for response type of objects not requests as from the documentation

But if you still want to set the headers in request then you could do something like

app.get('/', function(req,res){
    req.headers.abc ='xyz'; 
    console.log(req);
});

req are stored in req.headers so you could add your custom headers here for application middle wares to use later.

Upvotes: 7

Related Questions