reactjs 获取错误--->已被CORS策略阻止:

5tmbdcev  于 2022-12-22  发布在  React
关注(0)|答案(1)|浏览(123)
// code of react js for post request ---->>>
-----------------------------------------------
export const BASE_URL = "http://localhost:8080";

export const myAxios = axios.create({
  baseURL: BASE_URL,
});

export const privateAxios = axios.create({
  baseURL: BASE_URL,
  headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    
  },
 
});

privateAxios.interceptors.request.use(
  (config) => {
    const token = getToken();

    if (token) {
      // config.headers.common.Authorization = `Bearer ${token}`;
      config.headers["Authorization"] = `Bearer ${token}`;
      // console.log(config);
    }

    return config;
  },
  (error) => Promise.reject(error)
);

export const createPost = (user) => {
  return  privateAxios
    .post("/profile/v2/add/post", user)
    .then((val) => {
      console.log(val);
    })
    .catch((err) => console.log(err));

};
-----------------------------------------------------------------------------------------------
// cors config in spring boot ---->>>>

@Bean
    public FilterRegistrationBean crossFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("Authorization");
        corsConfiguration.addAllowedHeader("Content-Type");
        corsConfiguration.addAllowedHeader("Accept");
        corsConfiguration.addAllowedMethod("POST");
        corsConfiguration.addAllowedMethod("PUT");
        corsConfiguration.addAllowedMethod("GET");
        corsConfiguration.addAllowedMethod("DELETE");
        corsConfiguration.addAllowedMethod("OPTIONS");
        corsConfiguration.setMaxAge(3600L);
        source.registerCorsConfiguration("/**", corsConfiguration);

        return bean;

    }

我尝试张贴,但我得到错误---〉〉
CORS策略已阻止从源"http://localhost:3000"访问位于"http://localhost:8080/profile/v2/add/post"的XMLHttpRequest:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头。

s4n0splo

s4n0splo1#

对于 Spring Boot 上的CORS配置,您可以使用实现WebMvcConfigurer的配置

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

相关问题