Read the directory

(1) – Understanding cross-domain resource sharing of CORS;

Deep cross domain Problem (2) – Using CORS to solve cross domain

Deep cross domain Problems (3) – Using JSONP to solve cross domain problems

Deep Cross domain Problems (4) – Using proxy servers to solve cross Domain problems (This paper)

In the above article, we learned from this, CORS, JSONP two ways to implement cross-domain requests.

Both of these methods require the coordination of the front and back ends to properly handle cross-domain problems. Today we introduce a method that does not require the front and back ends to cooperate, and the front end can be completed independently.

As we all know, the same origin policy is the standard that browsers need to follow.

NODE serves as the client

Here’s one of our guesses, and instead of following the same origin policy between non-browsers, let’s test it out:

NODE sends the POST method

Client:

const http = require('http');

const options = {
    hostname: '127.0.0.1'.// Be careful not to add the HTTP prefix here
    port: 4000.// Server port number
    path: '/'.// Access path
    method: 'POST'.headers: {
        'Content-Type': 'application/json; charset=utf-8',}};const request = http.request(options, (serverResponse) => {

    var body = ' ';

    serverResponse.on('data', (chunk) => {
        body += chunk;
    });

    serverResponse.on('end', () = > {console.log('The data is '+ body); })}); request.end();Copy the code

Server, making a POST request

PS: In the browser POST method, the content-type is application/json. , triggers a pre-request (see my previous article).

Server:

const http = require('http');

const data = { name: 'BruceLee'.password: '123456' };

const server = http.createServer((request, response) = > {

    if (request.url === '/') {
        response.end( JSON.stringify(data) ); }}); server.listen(4000, () = > {console.log('The server is running at http://localhost:4000');
});
Copy the code

Note: We did not add any header fields inside the server that were shared with CORS cross-domain resources.

Experimental results:

Testing results show that making requests through NODE can avoid the browser’s same-origin policy.

Proxy server

For proxy servers, you need to do the following steps:

  1. Accept client requests.
  2. Forwards the request to the server.
  3. Get the server response data.
  4. The response is forwarded to the client.

Here is a simple text analysis, and below is a diagram of the process:

This is how proxy servers work (PS: painted garbage, hahaha).

Implementing a proxy server

Now that you know how a proxy server works, let’s implement a proxy server using NODE.

Client:


      
<html lang="zh-CN">

<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>Ajax test</title>
</head>
     
<body>
    
    <script src="./node_modules/jquery/dist/jquery.min.js"></script>

    <script>
    var data = { name: 'BruceLee'.password: '123456' };

    $.ajax({
        url: "http://localhost:3000".type: "post".data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8'.success: function (result) {
            console.log(result);
        },
        error: function (msg) {
            console.log(msg); }})</script>
</body>

</html>
Copy the code

Again, you can test it with PUT, DELETE, etc.

Proxy server: port 3000

const http = require('http');

// Step 1: Accept the client request
const server = http.createServer((request, response) = > {
	
    // Proxy server, directly interact with the browser, also need to set: CORS header field
    response.writeHead(200, {
        'Access-Control-Allow-Origin': The '*'.// Set the optins method to allow access by all servers
        'Access-Control-Allow-Methods': The '*'.'Access-Control-Allow-Headers': 'Content-Type'});// Step 2: Forward the request to the server
    const proxyRequest = http.request({
        host: '127.0.0.1'.port: 4000.url: '/'.method: request.method,
        headers: request.headers
    }, (serverResponse) => {
        
        // Step 3: Receive a response from the server
        var body = ' ';

        serverResponse.on('data', (chunk) => {
            body += chunk;
        });

        serverResponse.on('end', () = > {console.log('The data is ' + body );
            
            // Step 4: Forward the response to the browser
            response.end(body);
        })

    }).end();

});

server.listen(3000, () = > {console.log('The proxyServer is running at http://localhost:3000');
});
Copy the code

Note that the proxy server, which connects directly to the browser, must also comply with the same origin policy of the browser,

Server: port 4000

const http = require('http');

const data = { name: 'BruceLee'.password: '123456' };

const server = http.createServer((request, response) = > {

    if (request.url === '/') {
        response.end( JSON.stringify(data) ); }}); server.listen(4000, () = > {console.log('The server is running at http://localhost:4000');
});
Copy the code

In order to keep it small, I have used more concise code, which you can try on yourself, such as: PUT, DELETE methods.

Experimental results:

Cross-domain requests were successfully avoided.

Now that we’re done, the proxy server solves the cross-domain problem without any setup in the background.

References and acknowledgements

  • NODE Official Documentation
  • https://blog.csdn.net/real_bird/article/details/52714535

Proxy servers are a common tool for modern front ends, as are reverse proxies, and many other ways to implement cross-domain requests.