Angular2 Headers Angular2 Headers laravel laravel

Angular2 Headers


A preflighted request with CORS means that an OPTIONS HTTP request is executed before the actual one. You switch from a simple request to the one since you add a custom header in the case of a GET method. This link could help you to understand what happens: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/.

FYI the Origin header is automatically added by the browser when executing a cross domain request.

I think your problem is within the Access-Control-Allow-Origin header. You must set the host that makes the call and not the address of the server. You should have this instead (if your Angular2 application is running on localhost:8080):

return $next($request)        ->header('Access-Control-Allow-Origin', 'http://localhost:8080')        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')        ->header('Access-Control-Allow-Headers', 'x-id');

Hope it helps you,Thierry


I had the same issue in my Angular2 application.The problem, as already stated, is that before every request made by the client a preflight request is sent to the server.

This kind of request have a type OPTIONS, and it's duty of the server to send back a preflight response with status 200 and headers set for accepting requests from that client.

This is my solution (with express):

// Domain you wish to allowres.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');// Request methods you wish to allowres.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');// Request headers you wish to allowres.setHeader('Access-Control-Allow-Headers', 'YOUR-CUSTOM-HEADERS-HERE');// Set to true if you need the website to include cookies in  requestsres.setHeader('Access-Control-Allow-Credentials', true);// Check if Preflight Requestif (req.method === 'OPTIONS') {    res.status(200);        res.end();}else {    // Pass to next layer of middleware    next();}

In this way, the client will be authorized and you will be able to set your custom headers in all the requests. In your case, you'll have to set x-id in the Access-Control-Allow-Headers option.


In your case the server has to respond to the preflight request with following headers:

Access-Control-Allow-Origin: *

X-Custom-HeaderAccess-Control-Allow-Methods: GET, POST, PUT, DELETE

Access-Control-Allow-Headers: x-id

Note that for the Access-Control-Allow-Origin HTTP header it's best practice to set the domain where the angular2 app is hosted explicitly instead of the * which is only necessary for public API's where you don't control all consumers!

I highly recommend you to read following article about CORS:

http://www.html5rocks.com/en/tutorials/cors/