How can I inject a custom HTTP Header into every request that SuperAgent makes?

前端 未结 3 605
情话喂你
情话喂你 2021-02-07 10:16

Clearly SuperAgent supports custom HTTP headers:

request
   .post(\'/api/pet\')
   .send({ name: \'Manny\', species: \'cat\' })
   .set(\'X-API-Key\', \'foobar\'         


        
3条回答
  •  情深已故
    2021-02-07 10:59

    I'd just make a separate module with something like this:

    myagent.js

    var superagent = require('superagent');
    
    var defaultHeaders = {};
    function isObject(obj) { return Object(obj) === obj; };
    
    function request(method, url) {
       return superagent(method, url).set(defaultHeaders);
    }
    
    request.set = function (field, value) {
       if (isObject(field)) {
          for(var key in field) this.set(key, field[key]);
          return this;
       }
       defaultHeaders[field] = value;
       return this;
    }
    module.exports = request;
    

    Usage

    var request = require('./myagent');
    request.set({'X-My-Header': 'foo'}); // sets the default
    
    request.get('/bar').send() // will send the default header
    

    The module behaves the same way as superagent but sets default headers before returning the Request object. See here

提交回复
热议问题