I get a CORS issue on Spring Boot. The Get Request works using the Spring's Java Configuration for CORs (using WebMvcConfigurer). POST requests don't work.
I tried not only the Java Configuration, but annotations(@CrossOrigin()) and Filters (Ordered into HIGHEST_PRECEDENCE). Annotations never seem to work for me -even for a Get Request.
My CORS filter(copied and pasted 22kar's answer): Spring Boot : CORS Issue
My WebMvcConfigurer:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:3000");
registry.addMapping("/greeting-posttest").allowedOrigins("http://localhost:3000");
// .allowedHeaders("Access-Control-Request-Method", "Origin", "Access-Control-Request-Headers")
// .allowedMethods("POST", "OPTIONS", "HEAD", "GET", "PATCH")
// .exposedHeaders("Access-Control-Allow-Origin");
}
};
}
My annotation-driven cors:
// @CrossOrigin(origins = "http://localhost:3000")
@PostMapping("/greeting-posttest")
public Greeting greetingPostTesting(@RequestBody String content) {
System.out.println("==== in greeting post ====");
Greeting newGreeting = new Greeting(counter.incrementAndGet(), content);
return newGreeting;
}
The JS that makes the request(from a react-redux app):
export function apiCall(method, path, data){
return new Promise((resolve, reject)=>{
return axios.post("http://localhost:8080/greeting-posttest",{content: "POSTING!"}, config).then(res=> {
console.log("successful");
console.log(res);
return resolve(res.data)
}).catch(err => {
console.log("caught in apiCall")
console.log(err);
return reject(err.response);
})
})
}
const config={
headers: {
'Origin': 'http://localhost:3000',
// 'X-Requested-With': 'http://localhost:3000',
'Access-Control-Request-Method' : 'POST, OPTIONS',
'Access-Control-Request-Headers': 'access-control-allow-origin'
}
}
EDIT: Browser Devtools response:
Forbidden header name: Origin
Forbidden header name: Access-Control-Request-Method
Forbidden header name: Access-Control-Request-Headers
Axios response:
Error:"Network Error"
As far as I know about Axios' response, Network error is given when no error status code can be suggested by Axios.
====================
My backend: https://github.com/eeasuper/testing123
my frontend: https://github.com/eeasuper/practiceNaverMockingWeb
my apicall in frontend: https://github.com/eeasuper/practiceNaverMockingWeb/blob/master/src/services/api.js
(backend file in frontend repository is irrelevant to this post.)