Jeresy CORS filter working but React rest GET failing still with header ‘access-control-allow-origin’ is not allowed

168 Views Asked by At

I create a rest react front end to talk to a Jersey servlet on tomcat on the back end for RH 8.6. When react tried to do on REST GET or POST commands I got the "‘access-control-allow-origin’ is not allowed according to header" error. So I then added the CORS filter which was suppose to fix the origin problem, but the react client is still failing. I have tried different filters but there is no change. I assume the problem is in the react GET fetch but it looks ok with me and gets a header back when mode: 'no-cors' is set. In the debugger the CORSFilter class gets the GET, but it does not reach the resource class endpoint so its getting rejected.

Using postman I have verified the CORSFilter is inserting the values in the response as you can see here.

POST http://localhost:8080/rtc-servlet/mcd/location

Headers from postman tool:
    Status Code: 200
    access-control-allow-credentials: true
    access-control-allow-headers: X-Requested-With, CSRF-Token, X-Requested-By, Authorization, Content-Type
    access-control-allow-methods: API, GET, POST, PUT, DELETE, OPTIONS, HEAD
    access-control-allow-origin: *
    access-control-max-age: 151200
    connection: keep-alive
    content-length: 701
    content-type: application/json
    date: Sat, 10 Dec 2022 02:52:19 GMT
    keep-alive: timeout=20

servlet code:

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        
         // *(allow from all servers) OR https://crunchify.com/
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        
         // As part of the response to a request, which HTTP headers can be used during the actual request.
        responseContext.getHeaders().add("Access-Control-Allow-Headers",
                "X-Requested-With, CSRF-Token, X-Requested-By, Authorization, Content-Type");
        
Also tried these options:
                "Access-Control-Allow-Headers", "origin, content-type, accept, authorization");

        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        
        responseContext.getHeaders().add("Access-Control-Allow-Methods", 
                "API, GET, POST, PUT, DELETE, OPTIONS, HEAD");
        
        // How long the results of a request can be cached in a result cache.
        responseContext.getHeaders().add("Access-Control-Max-Age", "151200");
    }
}

    @GET // read in updated/original files
    @Produces(MediaType.APPLICATION_JSON) // what format we send back
    public JsonObject getLocationValues() {
        System.out.println("Called location getLocationValues ");
        return locationRepository.readConfigFile(false);
    }

React Rest GET fetch:

const urll1 = "http://localhost:8080/rtc-servlet/mcd/location";

useEffect(() => {
    const fetchPost = async () => {
        await fetch(urll1, {
            // mode: 'no-cors',
            headers: {
                'Content-Type': 'application/json',
                "Accept": "application/json",
                "Access-Control-Allow-Origin": "*",
            },
        })
            .then((response) => {
                if (response.ok) {
                    response.json().then(data => {
                        console.log("response fetchPost :" + JSON.stringify(data));
                        setPosts1(data);
                    });
                } else {
                    console.log("response was not ok");
                }
            })
            .catch((err) => {
                console.log(err.message);
            });
    };
    fetchPost();
}, []);

The console error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rtc-servlet/mcd/location. (Reason: header ‘access-control-allow-origin’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rtc-servlet/mcd/location. (Reason: CORS request did not succeed). Status code: (null).
NetworkError when attempting to fetch resource.

So does anyone see that I am doing wrong?

1

There are 1 best solutions below

0
John kerich On

After read the CORS not working posts in stackoverflow again I came across a commit about getting the origin from the header and then setting Access-Control-Allow-Origin to it vs. "*" and react on port localhost:3000 started to get responses back from the localhost:8080 servlet (origin is being set to "localhost:3000"). This was the forum string if you want to read up on it:
How to enable Cross domain requests on JAX-RS web services?.

So the change in the filter class is as follows:

String origin = requestContext.getHeaderString("origin");
if ((origin != null) && (!origin.isEmpty())) {
    headers.add("Access-Control-Allow-Origin", origin);
} else {
    // *(allow from all servers) OR https://crunchify.com/
    headers.add("Access-Control-Allow-Origin", "*");
}

headers.add("Access-Control-Allow-Credentials", "true");

and in the js script "Access-Control-Allow-Origin": "*" was deleted:

await fetch(urll1, {
    headers: {
        'Content-Type': 'application/json',
        "Accept": "application/json"
    },
})

I am not sure if I now need the else since "*" didn't work for me, but I left it in. If its not needed or I am just doing something that sort of works because I am using firefox please let me know.