javascriptajaxreactjsecmascript-6superagent

superagent set custom request headers es6 not Access-Control-Request-Headers


I know this is addressed in this post but I am still having trouble setting a custom header using ES6 and am wondering if anyone has run into this issue? The problem is when is set the header using .set I only set the Access-Control-Request-Header to the label I want to set it and the value is lost. I want to set a custom field on the request header using superagent and not sure how.

Let's say I am running this in my app (client)

import ajax from 'superagent'

ajax.get(baseURL + "/query/")
    .query({q: "SELECT Id FROM USER WHERE Id=" + id})
    .set('X-Authorization', 'Oauth ' + token)
    .set('Content-Type', 'application/json')
    .end((error, response) => {
        if(errro) { console.log(error); }
    }

the header the get request makes contains:

Access-Control-Request-Headers:content-type, x-authorization

under Request Headers in the network tab of the browser debugger. I want to set the headers of the get so that under Request Headers in the network tab of the browser dubugger I see:

X-Authorization:  some_token
Content-Type: application/json

Does anyone have any ideas on how I can set the Request Headers to have any field/value I want using ES6 and superagent?

thanks to all in advanced!


Solution

  • try adding the following code to your script, before get is called.

    ajax._defaultHeaders = {};
    
    function isObject(obj) { return Object(obj) === obj; };
    
    ajax.set = (function (field, value) {
       if (isObject(field)) {
          for(var key in field) this.set(key, field[key]);
          return this;
       }
       this._defaultHeaders[field] = value;
       return this;
    }).bind(ajax)