我正在尝试使用 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);
});
};
但我总是在控制台中收到此错误: 从源“http://localhost:3000”访问“http://localhost:8080/api/v1/category”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。
还有这个: xhr.js:258 GET http://localhost:8080/api/v1/category net::ERR_FAILED 两次
当我尝试使用 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;
}