Vassilis Pits
Vassilis Pits

Reputation: 3848

Add headers in all outgoing http requests using request module of ExpressJS, is it possible?

I'm using the request module for NodeJS.

I was wondering, Instead of adding the headers in every request by hand like the docs.

ex.

var options = {
  url: myuRL,
  headers: {
    'myHeader': 'headerVal'
  }
}

request(options ,callback);

Is it possible with a middleware or something to inject the headers in ALL requests?

I tried by creating this middleware:

const addHeaders = function (req, res, next) {
  req.header('myHeader', 'MyVal');
  next();
};
module.exports = addHeaders;

It works on all http requests except those created with the request module.

NOTE: I mean to all me outgoing request not to the incoming.

Upvotes: 1

Views: 4844

Answers (1)

agoldis
agoldis

Reputation: 1067

From https://www.npmjs.com/package/request#convenience-methods:

request.defaults(options) This method returns a wrapper around the normal request API that defaults to whatever options you pass to it.

//requests using baseRequest() will set the 'x-token' header 
var baseRequest = request.defaults({
  headers: {'x-token': 'my-token'}
})

You can wrap the request module inside your own module to prevent redefining the header every time, for example, create myRequest.js

var request = require('request');
var myRequest = request.defaults({
  headers: {'x-token': 'my-token'}
})
module.exports = exports = myRequest;

[EDIT] Working example:

myRequest.js

const request = require('request');
const myRequest = request.defaults({
  headers: {'x-token': 'my-token'}
});
 module.exports = exports = myRequest;

index.js

const myRequest = require('./myRequest.js');
const options = {
  url: 'https://google.com'
};
myRequest(options, (err, res, body) => {
  if (err) {
    console.error(err);
  }
  else {
    console.log(res.req._headers);
  }
});

Running index.js:

$ node ./index.js
{ 'x-token': 'my-token',
referer: 'https://google.com/',
host: 'www.google.com' }

I've pushed the example to https://github.com/agoldis/stackoverflow_37549654

Upvotes: 1

Related Questions