First of all, the browser message is cross-domain. It’s not that the server didn’t return it, it’s that the server did return it, but the browser intercepted it.

Var httpProxy = require(‘http-proxy’))), and returns the result of the request to the target server. Since the browser requests a local path, there is no cross-domain problem.

Proxy serverhttp-proxy

Node-http-proxy is an HTTP programmable, WebSockets enabled proxy library. It is suitable for implementing components such as reverse proxies and load balancing.

var httpProxy = require('http-proxy')
// Create a proxy server
 var proxy = httpProxy.createProxyServer({})
 var proxyEvents = [
    'error'.'proxyReq'.'proxyReqWs'.'proxyRes'.'open'.'close'
  ]
  // Register proxy server events
  proxyEvents.forEach(eventName= > {
      proxy.on(eventName, handlers[eventName])
  })
Copy the code

The HTTP proxy – middleware configuration

The following example solves the cookie cross-domain problem:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The proxy cross-domain</title>
</head>
<body>
    <script>
        var xhr = new XMLHttpRequest();

        // Front-end switch: whether the browser reads and writes cookies
        xhr.withCredentials = true;

        // Access the HTTP-proxy-Middleware proxy server
        xhr.open('get'.'http://localhost:3000/login? user=admin'.true);
        xhr.send();
    </script>
</body>
</html>
Copy the code

Intermediate proxy services use http-proxy-middleware middleware,

// Intermediate proxy server
const express = require("express");
let proxy = require("http-proxy-middleware");
let app = express();

app.use(
    "/",
    proxy({
        // Proxy cross-domain target interface
        target: "http://www.proxy2.com:8080".changeOrigin: true.// Modify the response header information to cross-domain and allow cookies
        onProxyRes: function(proxyRes, req, res) {
            res.header("Access-Control-Allow-Origin"."http://localhost");
            res.header("Access-Control-Allow-Credentials"."true");
        },

        // Change the cookie domain name in the response information
        cookieDomainRewrite: "localhost" // The value can be false, indicating no change})); app.listen(3000);
/ / the server
const http = require("http");
const qs = require("querystring");

const server = http.createServer();

server.on("request".function(req, res) {
    let params = qs.parse(req.url.substring(2));

    // Write cookies to the front desk
    res.writeHead(200, {
        "Set-Cookie": "l=a123456; Path=/; Domain=www.proxy2.com; HttpOnly" // HttpOnly: the script cannot read
    });

    res.write(JSON.stringify(params));
    res.end();
});

server.listen("8080");
Copy the code

Reference article:

Let you completely solve the cross-domain problem