kfa
kfa

Reputation: 2146

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

I am struggling with this issue today as I am implementing a cross-site API call. The worst thing is it works well from my local environment but once on heroku, it fails with the following error:

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

Here is the function triggering 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.

Upvotes: 14

Views: 22909

Answers (5)

liang0000zai
liang0000zai

Reputation: 1

The reason is that x-xsrf-token keyword is not in response header Access-Control-Allow-Headers.

I solved this problem in java using following solution:

rsp.setHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS,PUT,DELETE,TRACE,CONNECT");
rsp.setHeader("Access-Control-Allow-Headers", "cache-control,content-type,hash-referer,x-requested-with, x-xsrf-token");

if ("OPTIONS".equals(req.getMethod())) {
   rsp.setStatus(HttpServletResponse.SC_OK);
   return;
}

Upvotes: 0

Vasyl Petrov
Vasyl Petrov

Reputation: 380

I cleared cookies, this solved problem.

Upvotes: 2

arn-arn
arn-arn

Reputation: 1377

this helped me in java (expose the headers and then include in the allow headers). This will then show in your 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");

Upvotes: 0

Zakhar G
Zakhar G

Reputation: 569

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

Upvotes: 46

LeonardoX
LeonardoX

Reputation: 1303

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

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

see AngularJS: POST Data to External REST API

Upvotes: 12

Related Questions