Spring/ Boot 和React.js授权头的CORS配置错误

xxls0lw8  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(49)

我正在尝试使用jwt身份验证从React.js前端调用此API

const getCategory = () => {
    const token = localStorage.getItem("user");

    return axios
      .get("http://localhost:8080/api/v1/category", {
        withCredentials: true,
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      .then((res) => res.json())
      .then((data) => setCategory(data))
      .catch(function (error) {
        console.log(error);
      });
  };

字符串
但我总是得到这个错误在控制台x1c 0d1x:访问XMLHttp请求在'http://localhost:8080/api/v1/category'从起源'http://localhost:3000'已被CORS策略阻止:响应preflight请求不通过访问控制检查:没有'控制-允许-起源'头是存在于所请求的资源.
还有这个:xhr.js:258 GET http://localhost:8080/api/v1/category net::ERR_FAQs两次
当我从Postman尝试同样的事情时,它工作得很好。此外,我应该指定在此之前,我击中了用于生成身份验证令牌的POST请求:

const login = (email, password) => {
  return axios
    .post(API_URL, {
      email,
      password,
      headers: {
        "content-type": "application/json",
      },
    })

    .then((response) => {
      localStorage.setItem("user", response.data.token);
      return response.data;
    });
};


它工作得很好,我没有收到cors配置错误
Spring Back中的CORS过滤器看起来像这样:

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/api/v1/**")
                .allowedOrigins("http://localhost:3000/")
                .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
                .allowedHeaders("Authorization","*")
                .exposedHeaders("Authorization")
                .allowCredentials(true)
                .maxAge(3600);
    }
}


我已经把它作为一个类添加到我的项目目录中。我也试着把它添加到我的主应用程序文件中:

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:3000/");
        config.addAllowedHeader("*");
        config.addExposedHeader("Authorization");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**", config);
        return source;
    }

xkrw2x1b

xkrw2x1b1#

如果你把样板上的最后一个去掉,你能试一下吗?

.allowedOrigins("http://localhost:3000")

字符串

相关问题