1

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.)

DP Park
  • 815
  • 1
  • 9
  • 19
  • What’s the exact error message shown in the browser devtools console? – sideshowbarker Jan 29 '19 at 09:09
  • The error message you get from running the axios.get in your frontend JavaScript code is what’s relevant. The error message you get from the curl command isn’t really relevant, and anyway you also haven’t shown the curl invocation which causes the error — instead you’ve just shown the curl command you use to make the OPTIONS request. Regardless, the curl error message you cite just indicates you made some syntax error or shell-quoting/escaping error in the curl invocation; it doesn’t indicate a problem with the server. – sideshowbarker Jan 29 '19 at 09:10
  • @sideshowbarker From FireFox, I get something along the lines of "Because of 'Same-Origin-Policy' access has been blocked. Source: CORS request has not succeeded," then it leads me to this link: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed?utm_source=devtools&utm_medium=firefox-cors-errors&utm_campaign=default Then I get an Error logged from devtool saying: "Error: Network Error," which I think comes from the Axios api. – DP Park Jan 29 '19 at 10:02
  • @sideshowbarker I edited my post to show browser response in the bottom. I indeed had a syntax error, but it didn't change the results, and it gave a different response as written above. – DP Park Jan 29 '19 at 10:50
  • 1
    You need to remove the entire `config={ headers: { … }` part from your axios.post call. Browsers don’t allow you to set the Origin header from your frontend JavaScript code. The Origin header is controlled by the browser and set by the browser. Same for the Access-Control-Request-Method and Access-Control-Request-Headers. That’s why the browser console error message is telling you those are “forbidden” header names — that means you’re forbidden to set request headers with those names. – sideshowbarker Jan 29 '19 at 11:00
  • @sideshowbarker I removed config as the third param of axios.post, and the errors disappeared. The aforementioned Error log from the Axios api is still persisting to stay where it is. As far as I researched about that log from Axios, it throws that error before any status code error can be suggested by Axios. – DP Park Jan 29 '19 at 11:10

1 Answers1

0

With Spring Security I had it working with my React-Redux project on the cloud following this post. Furthermore following the instructions given by user bvulaj at the bottom of this github link made my React project work on localhost. My react version is 16.8.6 and my Spring version is 4.0.0.

DP Park
  • 815
  • 1
  • 9
  • 19