首页 > 解决方案 > Axios CORS 错误(403)甚至服务器允许所有

问题描述

我尝试使用 Axios POST 请求从 Springboot 服务器获取 jwt 令牌,但出现以下错误:

xhr.js:166 OPTIONS url net::ERR_ABORTED 403
Access to XMLHttpRequest at 'url' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

似乎它无法通过带有“Access-Control-Allow-Origin”标头的预检请求。所以我在标题上配置了“Access-Control-Allow-Origin”,但不知何故它仍然无法正常工作。

这是代码:

反应:

return Axios({
      method: 'post',
      url: 'url',
      data: qs.stringify(json),
      headers: {
      'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'authorization': 'Basic token',
      },
    });

弹簧靴:

 @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration conf = new CorsConfiguration();
        conf.setAllowedOrigins(Arrays.asList("*"));
        conf.setAllowedMethods(Arrays.asList("POST", "GET", "OPTIONS", "DELETE", "PUT"));
        conf.setAllowedHeaders(Arrays.asList("Content-Type", "X-Requested-With", "accept,Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", "Authorization", "Cache-Control", "Access-Control-Allow-Origin"));
        conf.setAllowCredentials(true);
        conf.setMaxAge(3600L);
        ...
    }

标签: springspring-bootcorsaxios

解决方案


试试这个,默认情况下允许所有标题和 URL 只是为了检查

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedOrigins("*")
            .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS").allowedHeaders("*")
            .allowCredentials(true).maxAge(MAX_AGE_SECS);
}

你的网址也不应该没有引号

return Axios({
  method: 'post',
  url: url,  // like this
  data: qs.stringify(json),
  headers: {
  'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'authorization': 'Basic token',
  },
});

最后只是做个笔记

检查您的 URL 是否在安全配置中被允许,否则您将得到 403

@Override
protected void configure(HttpSecurity http) throws Exception {
     http.authorizeRequests()
     ...
     .antMatchers("/url*").permitAll()  // Allow whatever url is passed
     ...
     ;
}

推荐阅读