What is the CORS

CORS is a W3C standard, which stands for “Cross-origin Resource Sharing”. It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source.

In JSONP, we used the SRC attribute of the script tag to cross domains without being affected by the same origin policy, but this approach was not very elegant and did not make Ajax pleasant to use. To solve this problem happily, CORS was born.

In contrast to JSONP, CORS cross-domain is primarily server-side. As long as the server implements the CROS interface, we can use Ajax to cross-domain elegantly without even being aware of it when the client writes the code.

Based on the previous code example, we modify the server-side code in the demo:

// server.js const url = require('url'); Const HTTP = require(' HTTP ') http.createserver ((req, res) => {const data = {message: 'CORS successfully '}; Res. WriteHead (200, {' Access - Control - Allow - Origin: "http://192.168.141.1:8081"}); res.end(data.message); }).listen(3000); Console. log(' service started ');Copy the code

As can be seen from the above code, we mainly add a field “access-Control-allow-Origin” to the response header, which mainly corresponds to the orgin field in the browser request. If the values of these two fields are inconsistent, the server will reject this request. Throws an error (this error is not recognized by the status code because the return status code might be 200)

We then write a normal Ajax request on the client side:

// index.html <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index.html</title> </head> <body> <script> const xhr  = new XMLHttpRequest(); XHR. Open (' GET 'and' http://127.0.0.1:3000 ', true); xhr.onreadystatechange = function() { if(xhr.readyState === 4 && xhr.status === 200) { alert(xhr.responseText); } } xhr.send(null); </script> </body> </html>Copy the code

As you can see, this is just a normal request, which is one of the benefits of CORS cross-domain, without having to write inelegant hack code like JSONP.

We open the client server address in the browser to get the target server data, and then view the result:

The cross-domain succeeded.

# # advantages

  1. The client requires no extra redundant code, elegant and simple
  2. POST requests are supported

# # shortcomings

Because of the need for additional browser support, so the browser version has requirements, there are compatibility problems, only support IE 10 or above