0
votes

I have a react app running on localhost:3000 and I try to consume calling REST API by java ee backend rest server, running on localhost:8080. I have enabled CORS on header.

I tried to make a form submit post request on my component.

fetchApi = () => {

    const url = 'http://localhost:8080/test/api/rest/Service/checkCode';

    var myHeaders = new Headers();

    myHeaders.append('Access-Control-Allow-Origin', '*');
    myHeaders.append('Access-Control-Allow-Headers', 'origin, content-type, accept, authorization');
    myHeaders.append('Access-Control-Allow-Credentials', 'true');
    myHeaders.append('Access-Control-Allow-Methods', ' GET, POST, PUT, DELETE, OPTIONS, HEAD');
    myHeaders.append('Content-Type', 'application/json');

    var myInit = {
        method: 'POST',
        headers: myHeaders,
        mode: 'cors',
        cache: 'default',
        body: JSON.stringify({
            code: '15465',
            name: 'Jack',
        })
    };

    fetch(url, myInit)

        .then(function(response) {

            if (response.ok) {
                return response.json();
            }
            else{
                throw new Error('Network response was not ok');
            }


        }).then(function(data){

        console.log(data);
        this.setState({items: data});

    }).catch(function(error){
        console.log('There has been a problem with your fetch operation: ' + error.message);
    })
};

I have errors in line:

 fetch(url, myInit):

OPTIONS http://localhost:8080/test/api/rest/Service/checkCode 500 (Erreur Interne de Servlet)

And CORS Error:

Fetch API cannot load http://localhost:8080/test/api/rest/Service/checkCode. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'ttp://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

1
At Java side you to enable the cors - RIYAJ KHAN
Its not exactly a solution but to test if the problem is on CORS you can set fetch option mode: 'no-cors' and disable CORS. - bennygenel
Remove all of the myHeaders.append('Access-Control-Allow…') stuff from your request code. Those are all response headers for servers to send back. Adding them to requests in your client code is just going to break things. - sideshowbarker
The response had HTTP status code 500 indicates some server-side failure occurs when that java server receives an OPTIONS request. You probably want to look through server logs on the server side to see what messages are logged there when that 500 internal server failure occurs. - sideshowbarker
Thanks for your help! I removed all of the myHeader.append('Access-Control-Allow...') and I put 'no-cors' mode now I only have POST localhost:8080/test/api/rest/Service/checkCode 500 (Erreur Interne de Servlet) and on console.log "network response was not ok". Yep I ll try to look server logs - Mushou8

1 Answers

0
votes

this is a backend issue not a frontend you should allow the CORS from the backend and this is depend on the technology that used in the backend i used spring boot in my backend so by adding this code to the security configuration will solve it

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}