Wednesday, September 14, 2016

Ionic 2 / Angular 2 / CORS: HTTP Headers not being sent with request

Leave a Comment

I'm working on a project using Ionic 2 (2.0.0-beta.10). I try to pass an authorization token with the request. However the header is not being sent. Also other headers I tried to pass with the request are not being sent.

let url = 'http://www.example.com/savedata'; let data = JSON.stringify({ email: 'test@test.com', password: '123456' });  let headers = new Headers();  headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'Bearer ' + "tokenContent");  let options = new RequestOptions({ headers: headers });  this.http.post(url, data, options).map(res => res.json()).subscribe(data => {                  console.log("it worked");  }, error => {                 console.log("Oooops!"); }); 

My REST API receives this request with the following headers:

Host:               www.example.com  Connection:         keep-alive   Access-Control-Request-Method:  POST     Origin:             http://evil.com/     User-Agent:         Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36    Access-Control-Request-Headers: authorization, content-type  Accept:             */*  Referer:            http://localhost:8100/?restart=794567    Accept-Encoding:        gzip, deflate, sdch  Accept-Language:        en-US,en;q=0.8   

The data (body) comes in correct, only the headers problem I cannot resolve. Any help would be very appreciated.

1 Answers

Answers 1

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.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment