Ionic 2 / Angular 2 / CORS: HTTP Headers not being sent with request
This question has an answer here:https://stackoverflow.com/a/45286959/4119650
Headers.append()
does not update the object, it returns a clone of it. By instantiating the Headers object and then calling headers.append()
, the result of that append
isn't being used.Instead, you may need to do this:
headers: Headers = new Headers().append('Content-Type', 'application/json').append('Authorization', 'Bearer ' + "tokenContent");
Headers
is deprecated anyway, and should be replaced with HttpHeaders
and HttpClient
.https://angular.io/api/common/http/HttpHeadershttps://angular.io/guide/http
Try to use HttpClient. It is easiest and latest one.
constructor(private http: HttpClient) {}......postData() { const httpHeaders = new HttpHeaders({ 'Content-Type' : 'application/json', 'Cache-Control': 'no-cache', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, DELETE', 'Access-Control-Allow-Headers': 'Origin, Accept, Access-Control-Allow-Origin, Content-Type, Authorization, X-Requested-With' }); let url = 'http://www.example.com/savedata'; let data = JSON.stringify({ email: 'test@test.com', password: '123456' }); this.http.post(url, data, { headers: httpHeaders, observe: 'response'}).subscribe(data => { console.log("it worked"); }, error => { console.log("Oooops!"); }); // Here you don't need to use map().}
If you are calling REST API (example.com in your example) that is located on a different domain from your Angular 2 / Ionic app ( evil.com in your example), then you need to configure REST API server to return this header:
Access-Control-Allow-Origin: http://evil.com
Which will allow the browser to send async HTTP requests from evil.com host to the rest api server.
It is done by enabling CORS on the rest api server, you can read about it a bit more.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Several libraries for the backend that enable cross origin requests:
https://github.com/expressjs/cors - NodeJS/Express
https://pypi.python.org/pypi/Flask-Cors/ - Python cors library for Flask
and the list continues for almost any other backend framework.