
These headers are used to tell the server what the following actual CORS request contains. In any access control request, the Origin header is always sent.Īnd Access-Control-Request-Headers might also be a comma separated array. Together with the Origin: header they are all we need for the request. It is called a preflighted request and has the following Headers: Request Method: OPTIONSĪccess-Control-Request-Headers: content-type Open up the dev tools network tab, the request sent by the browser is not the request we created by JavaScript. The console has the following error:įailed to load Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. This is not the end of story, let's try to add some header to our request as 'Content-Type': 'application/json'. You may also specify "*" as a wildcard, thereby allowing any origin to access the resource. In the response, we have the header we just added: Access-Control-Allow-Origin: This allows our to have access to the API endpoint. This is added by the browser automatically. Open up the dev server and check the request and response, you can find the Origin: header in the request.

I've prepared a simple KOA server to demonstrate the idea. When developing, your frontend web app is running on a different port from your backend server.You would like to provide a public API to be consumed by any client, or clients specified by a whitelist.Resources you would like to be loaded from separate domains like images, CSS and script files.However, there are some cases we want to enable cross-origin resource sharing. You can find more detailed explanations on wiki. For example, cannot be accessed by because the port is different. Web pages are under the restrictions of same-origin policy, which means scripts contained in a web page cannot access data in another page with different origin.

What is a preflighted request/response?Ī practical guide for things you need to know about enabling Cross-Origin Resource Sharing (CORS).A practical guide to CORS Thomas Wang's blog
