credit:https://medium.com/@baphemot

Translation: https://medium.com/@baphemot/understanding-cors-18ad6b478e2b




“Well.. Ok, but not enough.”


If you work with AJAX calls a lot, you’ve probably encountered the following error.



If you see this message, it means that the response failed, but you can still see the returned data under the Network TAB in the Console.

So, what’s going on here?

Cross-source Resource Sharing (CORS)

The behavior you encounter is a cross-domain implementation of the browser.

For security reasons, before cross-domain standardization, if you wanted to call a node in a different domain API, it didn’t exist. This call is blocked by the SAME-Origin policy.

CORS is designed to, one, make the requests you make represent you; Second, block those rogue JS requests; Third, this mechanism is activated whenever you send a request to:

1). Different domain names. (eg. Application calls api.com on example.com)

2). Different subdomains. (eg. Application calls api.com on example.com)

3). Different ports. (eg. Application calls example.com:3001 on example.com)

4). Different agreements. (eg. Application calls example.com on example.com)

With this mechanism, we can prevent scripting attacks by hackers that replace your authentication information when you log on to, say, a bank’s website.

If your browser tries to make a ‘not easy’ request (e.g. A request contains cookies, Or content-type is not Application/X-W-form-urlencoded, multipart/form-data or text-plain) and there is a mechanism called preflight, An options request is then sent to the server. If the server responds without a specific HEADERS, subsequent ‘simple’ GET or POST requests will still be sent, but the browser will not allow JS to access the received data.

If you explicitly want to add cookies, customize headers and other features, then the request is no longer an ‘easy’ request. The server will not respond properly and the request will not be sent.


Access – Control – Allow – What?

CORS uses very few HTTP headers (both in request and response), but there are a few things you should understand and be able to use in your work:

Access-Control-Allow-Origin

This request header is usually returned by the server, and its value represents which domain name you have access to. Its value can be:

  • *Allows access to any domain
  • A security-verified domain name (eg.example.com)

If you are asking clients to send authentication headers, such as cookies, you cannot set access-Control-allow-Origin to * – it must be a securely authenticated domain name!

Access-Control-Allow-Credentials

If a server supports authentication through cookies, the request header must be included in the response.

True is its only valid value.

Access-Control-Allow-Headers

A comma-separated list of request headers that represent what the server is willing to support. (e.g. X-authentication-token, you need to include it in the ACA header and return it to the previously mentioned Options request, otherwise your request will be blocked)

Access-Control-Expose-Headers

Similarly, the request header contains a list of user-available Headers that appear in the actual response and are available to the client. All other headers are blocked.

Access-Control-Allow-Methods

This one is relatively simple and stores all HTTP request types supported by the server (such as GET, POST).

Origin

The part of the client request header whose value contains the domain name at which the client app is started. For security reasons, browsers will not allow you to override this value.


How do I eliminate ‘CORS’ errors

You have to admit that CORS is not a ‘mistake’. It is an anticipatory mechanism to protect the user, you, and the site to which you are sending the request.

Sometimes the lack of a proper request header is a client error (eg. Missing validation information such as an API key).

Here are some ways to “fix errors”, depending on the scenario you’re using:

A – I develop front end, I know back end, listen to me;)

Well, that’s certainly the best case scenario, where you can implement a reasonable CORS response on the server side of your request. If an API is using Node’s Express framework, all you need to do is use the CORS package. If you want to make your site more reasonably secure, you may want to consider using a whitelist for access-Control-Allow-Origin headers.

B – I develop the front end, I am not familiar with the back end and need a temporary solution 🙂

This is the second best case, because this is case A, but with some time constraints. If you want to fix this temporarily, you can make your browser ignore CORS, for example, use ACAO Chrome, or run the following flags when using Chome:

chrome --disable-web-security --user-data-dirCopy the code

Important: Remember that this command applies to all web sites and exists throughout the browser session. Please use with care.

Alternatively, you can use devServer.proxy (assuming you use Webpack to serve your app) or use a Cers-as-a-service solution such as cors-anywhere.herokuapp.com/

C – I develop the front end, I want to adjust the back end? Nonexistent: ‘(

Well, now things get complicated. First, you should probably want to understand why the server is not sending the correct request header.

Maybe they’re not allowed to use third-party library apps to access them? Maybe their apis are only for server-side applications, not browsers? Maybe you didn’t send the token for authentication at the time of the request?

If you still think you can get data through the browser, you should write your own proxy between the browser application and the API, as we did in Plan B.



                                        Adding a proxy in the middle

The proxy server does not have to run on the same domain as your application. Simply make the proxy server support CORS when communicating with clients. Support for CORS is not required when communicating with apis.

You can write your own platform, or use an existing solution, for example

www.npmjs.com/package/cor…

Keep in mind that this approach can be a security risk if you want to support validation.


More about CORS

If you want to learn more about CORS, I recommend you to check out MDN Article for more details.