What is the meaning of CORS?

I always see the word CORS related to an error occurred when trying to make a request XmlHttpRequest for a given page, which does not have the same domain as the source.

Example:

XMLHttpRequest cannot load http://localhost / . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://127.0.0.1 ' is therefore not allowed access.

But what is the meaning of the word CORS ?

Is this word used to define the error that occurred, or some Browser Security Policy?

Author: Wallace Maxters, 2016-08-04

1 answers

Cors (Cross-Origin Resource Sharing in English and cross-source resource sharing in English ) is an agreement on how to exchange resources between browser and server when the browser tries to access a domain other than the one you are browsing.

Is a set of rules, a W3C specification, for what kind of resources can be accessed, and how to limit them. These rules are implemented by browsers/browsers, and it is this (the browser) that limits access.

These rules were imposed for security reasons. To prevent scripts on the page from freely accessing and ordering other sites and interacting with them.

On the server side you may or may not "open" the port to one, several or all requests/domains. This implementation is language specific but basically implies that there are headers present that the browser can read:

Access-Control-Allow-Origin: * // <- aberto para todos
Access-Control-Allow-Origin: http://example.com:8080 http://foo.example.com // <- só estes dois dominios podem aceder

In relation to error:

XMLHttpRequest cannot load http://localhost / . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://127.0.0.1 ' is therefore not allowed access.

When the browser reads the url for example http: it assumes that it is an external url. Actually http://localhost/ should be interpreted as "same domain" but because of http the browser thinks which it is not... To solve this problem, which also applies to online domains, relative paths should be used, not absolute paths with http... etc.

More reading:

. Wikipedia: https://pt.wikipedia.org/wiki/Cross-origin_resource_sharing

. W3C: https://www.w3.org/TR/cors/ in English

. DND: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS Em English

 22
Author: Sergio, 2016-08-04 16:43:10