【问题标题】:Preflight request doesn't pass access control check: It does not have HTTP ok status预检请求未通过访问控制检查:它没有 HTTP ok 状态
【发布时间】:2020-11-12 12:57:25
【问题描述】:

我正在尝试使用 axios 从 api Spring Boot 获取数据。

如果我用 InsomniaPostman 调用 api 它按预期工作,我有如下数据:

[
  {
    "id": 2,
    "username": "Admin",   
    "profil": null,
    "enabled": true,
    "roles": [
      {
        "id": 1,
        "name": "Admin"
      }
    ]
  }
]

但是使用 axios 或者 fetch 会抛出 Cors 错误:
Access to XMLHttpRequest at 'http://localhost:8181' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

所以我很困惑,为什么使用 axios 时没有将标头数据传递给服务器?我不能拥有Authorizationtest

后端配置:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*");
        }
    };
}

axios 请求:

function getData() {
    const baseURL = 'http://localhost:8181';
    const config: AxiosRequestConfig = {
      headers: {
        Authorization: 'Bearer TQyMDQ1OX0.C5oj83xiEAnRVdXZ24hpZnoRjCA8QsiN23kxylQCwdWCyTJyZOKcH_b4E5Ktv3A0ACVs4mj1XhrmqMJT_MHkeQ',
        test: 'test-data',
        'Access-Control-Allow-Origin': '*',
      },
    };

    axios.get(baseURL, config).then((result) => {
      console.log(result);
    });
  }

我想我错过了什么。 请帮忙

【问题讨论】:

    标签: javascript java reactjs spring-boot axios


    【解决方案1】:

    我不知道你的控制器中间有什么,但你可以尝试删除 AxiosRequestConfig。

    function getData() {
      const baseURL = 'http://localhost:8181';
      axios.get(baseURL).then((result) => {
        console.log(result);
      });
    }
    

    如果请求类型是POST类型

    function getData() {
      const baseURL = 'http://localhost:8181';
      axios.post(baseURL).then((result) => {
        console.log(result);
      });
    }
    

    【讨论】:

      【解决方案2】:

      我找到了解决方案。我通过将此行添加到我的 spring 安全网络配置来修复它

      protected void configure(HttpSecurity httpSecurity) throws Exception {
              httpSecurity.cors();
      //other configs
       }
      

      【讨论】:

        【解决方案3】:

        我通过添加这一行来修复它

        httpSecurity.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        

        【讨论】:

          猜你喜欢
          • 2020-01-14
          • 2020-08-21
          • 2020-06-06
          • 1970-01-01
          • 2020-02-11
          • 2019-05-25
          • 2020-07-31
          • 2019-07-07
          • 2020-08-27
          相关资源
          最近更新 更多