poutyboi
poutyboi

Reputation: 149

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!

Upvotes: 0

Views: 1988

Answers (2)

Inweo
Inweo

Reputation: 183

used to have similar problem with Spring Boot application and React JS on frontend.

When I dump headers that were attached to RQ I used to see only headers with pattern:

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

however that was problem connected with my backend application, NOT with superagent on frontend. I had to turn on cors() in WebSecurityConfig to look similar to this one:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable()
            .cors().and()
            .authorizeRequests().antMatchers("/auth/login", "/auth/register").permitAll().
            anyRequest().authenticated().and().
            exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

so as you can see problem was with Spring configuration, not with Superagent,

Regards R.

Upvotes: 1

qballer
qballer

Reputation: 2111

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)

Upvotes: 1

Related Questions