Series of articles:

  • [little brother, cross domain want to understand] JSONP
  • 【 little brother, cross domain want to understand 】CORS foundation
  • 【 little brother, cross domain want to understand 】CORS advanced
  • NGINX reverse proxy
  • [little brother, cross-domain to understand] ServerProxy

inPrevious postIn, we learned together about the first cross-domain processing schemeJSONPThis method is relatively primitive, the advantage is good compatibility, even modern front-end is not heard ofIE 6You can run all the way up. But goose, that’s all it’s good for. Its disadvantages are: only support GET requests, cumbersome configuration (both front and back ends need to adjust the code), register various callback functions on window, poor development experience….

CORS

Since the JSONP solution has many shortcomings and is old, let’s take a look at a more modern cross-domain solution called CORS

compatibility

The compatibility list from the MDN website is as follows:

Ie 10 runs, enough to satisfy the needs of modern front-end developers.

Concept 😳

Conceptual things here MDN occasionally needs ladders, bring your own.

Build cross-domain environments

Let’s start by creating a cross-domain environment based on our sample project from jSONPcross-domainFirst, create the CORS directory under the fe and BE directories. Next, add them separatelyindex.htmlindex.js. The modified project directory is shown below.

Fe/Cors /index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CORS implementations cross domains</title>
</head>
<body>
    <h3>CORS implementations cross domains</h3>

    <script>
        var xhr = new XMLHttpRequest()
        xhr.open('GET'.'http://localhost:8888')
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr.responseText)
            }
        }
        xhr.send()
    </script>
</body>
</html>
Copy the code

A very simple Ajax request, no.

Back-end code be/cors/index.js

const http = require('http');

const PORT = 8888;

// Create an HTTP service
const server = http.createServer((request, response) = > {
  response.end("{name: 'quanquan', friend: 'guiling'}");
});

// Start the service and listen on the port
server.listen(PORT, () = > {
  console.log('Service started successfully, listening:', PORT);
});
Copy the code

The project code at this point

Find some signs

Once the code environment is ready

  • Start with the back-end codenode ./be/cors/index.js
  • Next, start the front-end Web containerlive-server ./fe/cors
  • Open your browser and visit http://localhost:8080/
  • Open the Console and switch to the Console TAB
  • Refresh the browser

Let’s take a closer look at this familiar error. The previous paragraph tells us that our request was blocked. It just tells us the solution. The solution'Access-Control-Allow-Origin' header is present on the requested resource.It’s such an obvious hint, don’t we try??

Add access-Control-allow-origin to the response header

In response to the browser error, we figured out that he wanted us to add access-Control-Allow-Origin to the response header, so we modified our back-end code.

const http = require('http');

const PORT = 8888;

// Create an HTTP service
const server = http.createServer((request, response) = > {
  response.setHeader('Access-Control-Allow-Origin'.The '*');
  response.end("{name: 'quanquan', friend: 'guiling'}");
});

// Start the service and listen on the port
server.listen(PORT, () = > {
  console.log('Service started successfully, listening:', PORT);
});
Copy the code

The modified code.

Huge PS: After modifying the back-end code, be sure to
Restarting the Node Service

Refresh the browser and I’m a good boy. Good 😄

The downside of JSONP is that it only supports GET requests, which are modern cross-domain requests. Can CORS support other requests?

Support for other request methods

As a modern cross-domain problem solution, it should be able to solve multiple request modes. All talk, no practice. Let’s try 😄

Changing front-end code

/ / change before
xhr.open('GET'.'http://localhost:8888')
/ / after the change
xhr.open('POST'.'http://localhost:8888')
Copy the code

Why don’t you take a look at the code in the browser?

There was no problem and the returned data was printed smoothly. No errors were reported.

Try the PUT request while you’re excited

Change the front-end code again

/ / change before
xhr.open('POST'.'http://localhost:8888')
/ / after the change
xhr.open('PUT'.'http://localhost:8888')
Copy the code

Why don’t you take a look at the code in the browser?

Oh, my god? Very familiar error, but do not mistake, this error and the previous error is very similar, but the key words are not the same. Based on previous experience, adding access-Control-allow-methods response headers to the back end should work.

The back-end code

const http = require('http');

const PORT = 8888;

// Create an HTTP service
const server = http.createServer((request, response) = > {
  response.setHeader('Access-Control-Allow-Origin'.The '*');
  response.setHeader('Access-Control-Allow-Methods'.'PUT');
  response.end("{name: 'quanquan', friend: 'guiling'}");
});

// Start the service and listen on the port
server.listen(PORT, () = > {
  console.log('Service started successfully, listening:', PORT);
});
Copy the code

Why don’t you take a look at the code in the browser?

Successful 😄

Other HTTP methods handle the same as the PUT method. One can draw inferences from another.

You need to add a token to your request

Since this is modern development, session management is usually done using JWT (I’ll probably write about it later), and one of the shining signs of JWT is that the request header adds a JWT token. Good men do not speak dark words.

Modify front-end code:

// Add a line
xhr.setRequestHeader('token'.'quanquanbunengshuo')
Copy the code

Why don’t you take a look at the code in the browser?

I’m sure you’ve already figured out my routine.

The back-end code

// Add a line
response.setHeader('Access-Control-Allow-Headers'.'token');
Copy the code

Why don’t you take a look at the code in the browser?

So far, the cross-domain request is successful, the request method is compatible, and the custom request header works. Is it lucky enough to eat chicken?

To Network TAB, which has been kicked out of service

We’ve been looking at the browser’s Console TAB the whole time, and for a communications article, it’s a bit awkward to skip Network.

If it exists, it’s definitely something to look at, so let’s switch TAB to Network.

Iuv? Two requests, one OPTIONS and one PUT, what the hell is that?

The next episode: Just saw the Network there was a murder. Of course, if only you can use CORS to achieve cross-domain, so far there are no problems, used for interview is also a great drop. Next, let’s explore what happens with precheck requests and Cookie portability under CORS. Friday code word feel so tired…… About the little sister to spicy 😄