Angular2: X-XSRF-TOKEN not allowed by Access-Control-Allow-Headers headers

I am struggling with this issue today when I make a cross-site API call. Worst of all, it works well from my local environment, but once per hero, it fails with the following error:

XMLHttpRequest cannot load https://restcountries.eu/rest/v1/all . The X-XSRF-TOKEN request header field is not allowed by the Access-Control-Allow-Headers headers in the preflight response.

Here is the function that calls the call:

let observable = this._http .get(GEO_API_URL + query) .map(response => response.json()) .do(val => { this.cache = val; observable = null; }) .share(); return observable; 

Any idea?

Thanks.

+6
source share
4 answers

There was the same problem.
In my case, the reason was that the X-XSRF-TOKEN field was saved in my Chrome browser. And somehow Chrome added the header "Access-Control-Request-Headers: x-xsrf-token" to the OPTION request. In Firefox, the same page works fine; in Chrome incognito mode, too.
So I just delete this cookie field (X-XSRF-TOKEN) and all that.

+30
source

In my case, I had to add the value x-xsrf-token 'to the Access-Control-Allow-Headers header:

 header('Access-Control-Allow-Headers: Content-Type, x-xsrf-token') 

see AngularJS: POST data for an external REST API

+3
source

this helped me in java (expose headers and then include permissions in headers). This will then be shown in the HttpResponse object:

 response.addHeader("Access-Control-Expose-Headers", "header1"); response.addHeader("Access-Control-Expose-Headers", "header2"); response.addHeader("Access-Control-Expose-Headers", "header3"); response.addHeader("Access-Control-Allow-Headers", "Origin, header1, header2, header3, X-Requested-With, Content-Type, Accept"); 
0
source

Client (Angular 4)

 @Injectable() export class HttpService { private actionUrl: string; private headers: Headers; private options: RequestOptions; constructor(public _http: Http) { this.actionUrl = 'example.com'; this.headers = new Headers(); this.headers.append('Content-Type', 'application/json'); this.headers.append('Accept', 'application/json'); this.headers.append('Access-Control-Allow-Headers', 'Content-Type, X-XSRF-TOKEN'); this.options = new RequestOptions({ headers: this.headers }); } 

Server

GET, POST

1) Access-Control-Allow-Origin: '*'

OPTIONS

1) Access-Control-Allow-Origin: '*'

2) Access-Control-Allow-Headers: 'Content-Type, X-Amz-Date, Authorization, X-Api-Key, X-Amz-Security-Token, X-XSRF-TOKEN, Access-Control-Allow-Headers ''

3) Access-Control-Allow-Methods: "POST, GET, OPTIONS"

0
source

All Articles