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

▼魔方 西西 提交于 2019-12-20 19:43:54

问题


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.

回答1:


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




回答2:


This could be the late answer but I have used superagent-use plugin to inject a custom HTTP header in all the requests. First of all, you need to install superagent-use

npm install superagent-use --save

then require like this

// using plugin to intercept calls
var request = require('superagent-use')(require('superagent'));

then add the function as middlerware/interceptor

// interceptor used by superagent to add custom header for each request
request.use((req) => {
    req.header.custom_header = any_value;
    return req;
});

and finally

request
    .get(url)
    .query({ view: 'jsonView' }) // query string



回答3:


So in my case I needed to set a csrf token as default header in all my requests. You can write a simple wrapper function like this.

custom-agent.js

import SuperAgent from 'superagent';

const csrfToken = document.querySelector('meta[name=csrf-token]').content;

export default {
  fire(method, url) {
    return SuperAgent[method](url).set('X-CSRF-Token', csrfToken);
  }
};

Use it like this.

import Agent from './custom-agent'

Agent.fire('get', '/endpoint')
// => SuperAgent.get('/endpoint').set('X-CSRF-Token', csrfToken)


来源:https://stackoverflow.com/questions/31059462/how-can-i-inject-a-custom-http-header-into-every-request-that-superagent-makes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!