CORS, or Cross-resource Sharing, is a mechanism that uses additional HTTP headers to tell browsers to allow Web applications running on one Origin (domain) to access specified resources from different source servers. Simply put, browsers restrict cross-domain requests such as XMLHttpRequest and Fetch from within scripts for security reasons. That is, in Javascript, when we want to make a cross-domain Ajax request, the browser’s restrictions will cause the request to fail.

For example: in http://mysite.com/index.html, launched an Ajax request to http://api.yoursite.com/article/all/, will fail, if open the console log, will see output similar to the following:

Access to XMLHttpRequest at 'http://api.yoursite.com/article/all/' from origin 'http://mysite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Copy the code

At present, when developing regular Web projects, it is difficult to use the unified domain name in the process of development and coordination even if the unified domain name is used to access projects after the official launch, so it is necessary to master the processing of cross-domain requests.

A way to implement cross-domain requests

In addition to CORS, there are proxy servers and JSONP.

Proxy server

When it comes to using the server, we can immediately think of a popular reverse proxy server Nginx. Indeed, we can use the proxy_pass instruction of Nginx to achieve the purpose of proxy, but this method is often not intuitive, and generally requires front-end students to build relevant environment in the local can operate. It’s a bad choice.

In addition to Nginx, front-end students may say that now many popular frameworks are integrated with such functions, such as Vue. Js devServer, front-end students can write familiar Javascript code in the project to achieve the request of the proxy, and ultimately achieve cross-domain request, convenient coordination, But it’s also limited to development time.

JSONP

JSONP makes use of the mechanism that SRC references static resources without cross-domain restrictions. The front end will define a callback function to process the logic after the request is successful, and inform the server of the name of the callback function when requesting the server, and the server only needs to return the data according to the Javascript syntax. Just put it in the callback function. Something like this:

<! -- http://mysite.com/index.html -->
<script>
function callback(data) {
    / / the data processing
    console.log(data)
}
</script>
<script src="http://api.yoursite.com/article/all/?callbackFunc=callback"></script>
Copy the code

It is true that JSONP can successfully fetch data and the callback function is executed correctly, but before using JSONP, you need to understand its disadvantages:

  • Only HTTP Get requests can be made;
  • Error handling is not perfect, it is difficult to handle the error occurred during the request;
  • Security issues;
  • And so on.

To be honest, JSONP is rarely used in development projects these days, but this is just to give you an idea.

CORS

The CORS mechanism allows Web application servers to control cross-domain access and secure cross-domain data transmission.

Using Nginx as an example, let’s see how cross-domain access control can be implemented. Let’s see how to configure it:

http {
  # omit other...
  server {
    listen 80;
    server_name api.yoursite.com;
    charset utf-8;
    location / {
      include /usr/local/nginx/conf/cors; // omit other... }}}Copy the code

Thus, our API at http://api.yoursite.com/ supports cross-domain requests (regardless of the limitations of the program code).

The key is to include/usr/local/nginx/conf/cors; The cORS file contains the following contents:

Its core part, is to add the Access-Control-Allow-Origin HTTP header, and other parts of the content, is more fine-grained Control, such as different request methods can also set different HTTP headers to achieve the purpose of Control. With Nginx’s location directive, we can control when CORS is enabled on certain paths for finer grained control.

You can find it at enable-cors.org/server_ngin… Get the contents of the CORS file. The content of this document is only a model, not the only writing method, we can modify according to the needs of the actual use.

If you want to learn more about CORS, you can visit developer.mozilla.org/zh-CN/docs/…

How about not using Nginx?

If you understand the mechanics of CORS, this is not a problem.

This site provides implementations of different servers, Web frameworks, programming languages, enable-cors.org/server.html…

Django-cers-headers is the only way to implement Django. If Django is used, you can use Django-cers-headers. If Django is used for backend development, the front-end can happily make cross-domain requests.

Choose CORS

CORS is a better choice for cross-domain requests in terms of technological innovation and ease of use. As long as the back-end staff is (usually) configured, the front-end can call the back-end API without making any additional changes. This approach can be used both at development time and after launch without too much differentiation.

For those of you who haven’t used CORS yet, give it a try.