What is the meaning of CORS?

Asked

Viewed 5,957 times

22

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

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?

This word is used to define the error occurred, or some browser security policy?

  • 4

    Cross-Origin Resource Sharing. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

  • 2

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

1 answer

22


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

It’s a set of rules, a specification of W3C, to 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 safety reasons. To prevent scripts on the page from freely accessing and ordering other websites 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 is headers gifts 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 the 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 in the url for example http: it assumes it is an external url. Actually http://localhost/ should be interpreted as "same domain" but because of http the browser thinks it is not... To solve this problem, which also applies in online domains, one should use relative paths, and not absolutes with http... etc.

More reading:

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

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

. MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS In English

  • 1

    Thanks for the reply, I will add next to a reply I gave on the subject :D

  • 1

    To whom he gave -1: can comment to improve the response :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.