Add custom http headers to chai requests

Trung Tran picture Trung Tran · May 1, 2016 · Viewed 24.7k times · Source

I am building an app using node.js and testing with mocha + chai. Is there a way I can add custom headers to my GET and POST chai requests?

For example, I want something like (semi-pseudocode):

chai.request(server)
  .get('/api/car/' + data.car_id)
  .headers({'some_custom_attribute':'some_value'})
  .end(function(err, res) {
    //do something
  });

And likewise with post:

chai.request(server)
  .post('/api/car/')
  .headers({'some_custom_attribute':'some_value'})
  .send({car_id: 'some_car_id'})
  .end(function(err, res) {
    //do something
  });

Can someone help?

Thanks in advance!

Answer

alexmac picture alexmac · May 1, 2016

Use set function to set http headers:

chai.request(server)
  .get('/api/car/' + data.car_id)
  .set('some_custom_attribute', 'some_value')
  .end(function(err, res) {
    //do something
  });

setting-up-requests