I have a java server handling RESTful services on port 8080 using Glassfish/Jersey libraries (I do not have a web.xml file as I am hosting the services in the console app). I am running a webpack-dev-server with ReactJS on port 8081. In my ReactJS control I make a GET request from my RESTful service. When I make that call I get the following error:
Fetch API cannot load http://localhost:8080/realtime/initialize. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is the javascript code:
fetch('http://localhost:8080/realtime/initialize', {
method: "GET",
headers: {
mode: 'cors',
}
})
.then(function(response) {
console.log("financial services initialization ok");
this.setState({loginState: 1});
}).catch(function(err) {
console.log("financial services initialization error: " + err);
alert("initialized failed");
});
here is my java class:
package Application.Server;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import Application.Server.Contracts.GeneralResult;
@Path("/realtime")
public class RealTimeServices {
private int count = 1;
@GET
@Path("/initialize")
@Produces(MediaType.APPLICATION_JSON)
public GeneralResult initializeAccount() {
outputService.showMessage("connecting attempt: " + count);
count ++;
return new GeneralResult("request made");
}
}
I'm not sure what the problem is--I under cors is a browser security issue but don't understand what it means to handle cors. My attempt to fix it fails.
I've tried adding 'Access-Control-Allow-Origin' to the javascript http call but that still throws an error and I do not get the results back.
It seems like I need change something in the java code, but Im happy if there is something I can change in the javascript.
Thank you Matt