Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Clearly SuperAgent supports custom HTTP headers:

request
   .post('/api/pet')
   .send({ name: 'Manny', species: 'cat' })
   .set('X-API-Key', 'foobar')
   .set('Accept', 'application/json')
   .end(function(err, res){
     if (res.ok) {
       alert('yay got ' + JSON.stringify(res.body));
     } else {
       alert('Oh no! error ' + res.text);
     }
   });

My Question:

  • If I'm pulling down SuperAgent via npm, how can I inject my own HTTP header across all requests that SuperAgent makes?
  • Note: I'm entire willing to create a new npm package that extends SuperAgent if necessary.
like image 919
Jim G. Avatar asked Jun 25 '15 19:06

Jim G.


People also ask

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.

How do I add HTTP headers?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

How do I add a custom header in HTTP spring boot?

To set the custom header to each response, use addHeader() method of the HttpServletResponse interface. That's all about setting a header to all responses in Spring Boot.


1 Answers

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

like image 130
Christopher Tarquini Avatar answered Nov 01 '22 19:11

Christopher Tarquini