I have an issue with ionic3 framework when I run "ionic serve" and I make a request to a localhost server. The error I receive is:
Access to XMLHttpRequest at 'http://localhost:8080/myrestapi/myendpoint' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have searched around and I have added the Access-Control-Allow both in my server and in angular. From the angular point of view I have the following:
@Injectable()
export class Gateway {
private getBasicHttpOptions(): any {
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Access-Control-Allow-Origin', '*');
headers = headers.append('Content-Type', 'application/json');
let httpOptions: any = {headers: headers};
return httpOptions;
}
public getData(myparam: string): Observable<any> {
let httpOptions: any = this.getBasicHttpOptions();
let body: any = {
'param': myparam
};
return this.http.post("http://localhost:8080/myrestapi/myendpoint", body, httpOptions);
}
}
And then on the server side I have the following (javeEE6, SDK 7, glassfish 3.1.2):
@Path("/myrestapi")
@Stateless
public class Authentication {
@POST
@Path("/myendpoint")
@Consumes("application/json")
@Produces(MediaType.APPLICATION_JSON)
public Response myEndPoint(@HeaderParam("Content-Type") String contentType, String body){
return Response.status(200)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.type(MediaType.APPLICATION_JSON)
.entity("{ke1:'val1'}").type(MediaType.APPLICATION_JSON).build();
}
}
Whenever I call this.gateway.getData('aparam'); because I have in the debug mode my local server I cannot receive any request (from Postman it works fine). So it seems that it's from the client side that it doesnt send any request.
From Chrome from the network tools I have the following:
Any ideas?
CORS is an error raised by browsers to prevent unauthorized cross-origin requests to protect the end-users of the website - so, for example, chrome will raise it, but chromium which is run by Ionic will not - so it should only happen in the browser.
you have two options here:
Install a CORS chrome extension - since the mobile version will never get cors errors, it will be fine.
Enable CORS in glassfish/JEE, take a look at this SO question for details on how to do it - you can see in the response that you got from the server (response headers) - no access-control-allow-origin
header is returned.