28

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!

Trung Tran
  • 13,141
  • 42
  • 113
  • 200

1 Answers1

66

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

alexmac
  • 19,087
  • 7
  • 58
  • 69
  • and how to add post variables along with headers? – user269867 Jun 27 '17 at 22:42
  • 1
    @user269867 use `send` method for that. – alexmac Sep 06 '17 at 18:45
  • can you please guide me for simpler method to add multiple headers in `chai.request` because In my scenario I have more than 10 headers – Nazir Ahmed Nov 26 '18 at 12:42
  • 2
    @NazirAhmed try something like that: `let headers = [{ name: 'h1', value: 'v1' }, /* OTHER HEADERS */]; let chain = chai.request.get(/*YOUR REQUEST*/); headers.forEach(headers, header => chain = chain.set(header.name, header.value)); chain.end(/* DO SOMETHING */);` – alexmac Nov 30 '18 at 10:38
  • @alexmac Getting TypeError: chain.set is not a function – Ketav Dec 06 '18 at 06:51
  • This is my code: let chaiRequest = chai.request(app); for (let i = 0; i < headers.length; i++) { chaiRequest.set(headers[ i ].key, headers[ i ].value) } return chaiRequest .post(url) .send(params) // .set(headers[ 0 ].key, headers[ 0 ].value) .then(res => { return res }) – Ketav Dec 06 '18 at 06:52
  • @alexmac How to set header for multiple request without using .set() all the time, since I dont want to repeat myself. – Rupesh Sep 10 '19 at 04:43
  • 4
    notice that `set('header', value)` must be called after the HTTP method (get, post, etc.) – Pedro Andrade Feb 05 '20 at 21:00