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

xxls0lw8  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(162)

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

  1. const getCategory = () => {
  2. const token = localStorage.getItem("user");
  3. return axios
  4. .get("http://localhost:8080/api/v1/category", {
  5. withCredentials: true,
  6. headers: {
  7. Authorization: `Bearer ${token}`,
  8. },
  9. })
  10. .then((res) => res.json())
  11. .then((data) => setCategory(data))
  12. .catch(function (error) {
  13. console.log(error);
  14. });
  15. };

字符串
但我总是得到这个错误在控制台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请求:

  1. const login = (email, password) => {
  2. return axios
  3. .post(API_URL, {
  4. email,
  5. password,
  6. headers: {
  7. "content-type": "application/json",
  8. },
  9. })
  10. .then((response) => {
  11. localStorage.setItem("user", response.data.token);
  12. return response.data;
  13. });
  14. };


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

  1. @Configuration
  2. @EnableWebMvc
  3. public class CorsConfig implements WebMvcConfigurer {
  4. @Override
  5. public void addCorsMappings(CorsRegistry registry){
  6. registry.addMapping("/api/v1/**")
  7. .allowedOrigins("http://localhost:3000/")
  8. .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
  9. .allowedHeaders("Authorization","*")
  10. .exposedHeaders("Authorization")
  11. .allowCredentials(true)
  12. .maxAge(3600);
  13. }
  14. }


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

  1. @Bean
  2. CorsConfigurationSource corsConfigurationSource() {
  3. final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  4. final CorsConfiguration config = new CorsConfiguration();
  5. config.setAllowCredentials(true);
  6. config.addAllowedOrigin("http://localhost:3000/");
  7. config.addAllowedHeader("*");
  8. config.addExposedHeader("Authorization");
  9. config.addAllowedMethod("OPTIONS");
  10. config.addAllowedMethod("HEAD");
  11. config.addAllowedMethod("GET");
  12. config.addAllowedMethod("PUT");
  13. config.addAllowedMethod("POST");
  14. config.addAllowedMethod("DELETE");
  15. config.addAllowedMethod("PATCH");
  16. source.registerCorsConfiguration("/**", config);
  17. return source;
  18. }

xkrw2x1b

xkrw2x1b1#

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

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

字符串

相关问题