superagent设置自定义请求头es6而不是Access-Control-Request-Headers

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

本文关键字:Access-Control-Request-Headers es6 设置 自定义 请求 superagent      更新时间:2023-09-26

我知道这是在这篇文章中解决的,但我仍然在使用ES6设置自定义标题时遇到麻烦,我想知道是否有人遇到这个问题?问题是,当使用。set设置标头时,我只将Access-Control-Request-Header设置为我想要设置的标签,并且值丢失。我想使用superagent在请求头上设置一个自定义字段,但不确定如何。

假设我在我的应用程序(客户端)中运行这个

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); }
    }

get请求的报头包含:

Access-Control-Request-Headers:content-type, x-authorization
在浏览器调试器的网络选项卡中的Request Headers下的

。我想设置get的报头,以便在浏览器dubugger的网络选项卡中的请求报头下看到:

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

是否有人有任何想法,我如何可以设置请求头有任何字段/值,我想使用ES6和超级代理?

感谢所有先进的!

尝试在调用get之前将以下代码添加到脚本中。

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)

曾经在Spring Boot应用程序和React JS前端有类似的问题。

当我转储附加到RQ的头时,我过去只看到带有模式的头:

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

然而,这是与我的后端应用程序连接的问题,而不是与前端的超级代理。我必须在WebSecurityConfig中打开cors(),看起来类似于这个:

@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);

所以你可以看到问题是Spring配置,而不是Superagent,

的问候r .