I am working on an ionic application, the engine is a tomcat 9 that we currently have locally.
With npm start
we could test those services that communicate engine with interface but now that we are executing the application on the device, at the moment that it reaches the execution of some service it throws us the following CORS error:
Access to XMLHttpRequest at 'http://localhost:8085/recin-server/LoginServlet' 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.
Service.ts
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class HttpService {
private url = 'http://localhost:8085/recin-server/LoginServlet';
// Http Headers
headers: HttpHeaders = new HttpHeaders({
Accept: "application/json",
"Content-Type": "application/json; charset='utf-8'",
'Access-Control-Allow-Origin': '*',
'Authorization': 'authkey',
});
constructor(public http: HttpClient) {
console.log("Servicio login listo");
}
postLogin(login): Observable<any> {
return this.http.post(`${this.url}`, login, { headers: this.headers });
}
}
We have tried to send in the header of the service 'Access-Control-Allow-Origin': '*','Authorization': 'authkey',
without success.
I have read that the server can be modified to allow different urls, but I don't know what to add or where.
Following @OscarGarcia 's answer , I've read a bit of the tomcat documentation .
web.xml
I have added in the Tomcat server file the following:And I don't get that error anymore.