// 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;
}
i am trying to post but i am getting Error--->>
Access to XMLHttpRequest at 'http://localhost:8080/profile/v2/add/post' 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.
For CORS configuration on spring boot you can use configuration which implements WebMvcConfigurer
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.