Access Control Allow Origin issue in Angular 2

Access-Control-Allow-Origin is a response header, not a request header.

You need to have it appear on the response, not the request.

You have attempted to put it on the response:

resp.setHeader('Access-Control-Allow-Origin','*') 

… but it hasn’t worked.

This is probably because you haven’t put it on the response to the right request. The error message says:

Response to preflight request doesn’t pass access control check

You have done something to make the request preflighted. This means that before the browser makes the GET request you are trying to make, it is making an OPTIONS request.

This is, presumably, being handled by a different piece of code on your server so the line resp.setHeader('Access-Control-Allow-Origin','*') isn’t being hit.

One thing that causes a preflighted request to be made is the addition of request headers (other than a small number of exceptions). Adding Access-Control-Allow-Origin to the request will trigger a preflighted request, so the first thing to do to try to fix the problem is to remove Access-Control-Allow-Origin from the request.

If that fails, then you need to set up your server so it can respond to the OPTIONS request as well as the GET request.

Leave a Comment