0
votes

In my spring server I added this to enable cors:

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/*").allowedOrigins("http://localhost:3000");
            }
        };
    }

In my react.js client when I POST I get no error, but when I try to GET, I get error saying :

Access to XMLHttpRequest at 'http://localhost:8080/user/aweq' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Code :

let url=constant.serverURL+"user/"+this.state.username;
axios.get(url).then((res)=>console.log(res));

I even tried this :

let url=constant.serverURL+"user/"+this.state.username;
        axios.get(url,
            {headers:
                    {
                        "Content-Type": "application/json"
                    }
            }
        ).then((res)=>console.log(res));
2
Remove the entire headers block from the axios.get request. There’s no request body in a GET request, so there’s no need to set a "Content-Type": "application/json" header for the request.sideshowbarker

2 Answers

1
votes

I think the only thing, that should be fixed is

registry.addMapping("/**").allowedOrigins("http://localhost:3000");

so from /* => /**, to cover path /user/{username}

look also here for wildcards in path https://help.sumologic.com/03Send-Data/Sources/04Reference-Information-for-Sources/Using-Wildcards-in-Paths

1
votes

In your global cobfiguration you have provided wrong mapping, for enabling cors on all endpoints you need to provide the mapping as /** :

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }

Official doc