What is cross-domain

  1. Different domain name
  2. Different ports in the same domain

1. Simple scenarios

127.0.0.1:3000 access 127.0.0.1:4000 cross-domain, this is actually the browser same-origin problem, in fact, the server can respond normally

// For server 4000, just start the following code
res.setHeader('Access-Control-Allow-Origin'.'http://localhost:3000')
// Server 3000 can normally access 4000
Copy the code

2. Precheck request scenario

A client that sets the HEADERS X-token will start a precheck request

axios.get("/api/users", {headers: {'X-Token':'jilei'}})
Copy the code
  1. The client sends a/API /users request with the method options
  2. The server needs to reply and return the valid information to access the next request. The code is as follows
if (method == "OPTIONS" && url == "/api/users") {
    res.setHeader('Access-Control-Allow-Credentials'.'true');
    res.writeHead(200, {
        "Access-Control-Allow-Origin": "http://localhost:3000"."Access-Control-Allow-Headers": "X-Token,Content-Type"."Access-Control-Allow-Methods": "PUT"
    });
    res.end();
}
Copy the code
  1. Finally, the client can normally request get/API /users

3. Cross-domain cookies are saved

// Ajax client request place, add
axios.defaults.withCredentials = true

// The node server OPTIONS reply added
  res.setHeader('Access-Control-Allow-Credentials'.'true');

// Node tests the code
   console.log('cookie',req.headers.cookie)// Check whether cookies were returned last time
   res.setHeader('Set-Cookie'.'cookie1=va222; ')/ / set cookies
Copy the code

No refresh simple buried point

Const img = new Image() img.src='/ API /users? abc=123'Copy the code

The agent

Forward agent

Back in the days of dial-up Internet

  • Company internal personal PC -> company public agent software -> telephone line -> server – “a single service
  • Corporate proxy software can effectively cache accessed content, saving individuals access to the same content

The reverse proxy

In the age of high-speed Internet

  • Internal PC -> 5G -> server -> (front-end + back-end + multiple distributed servers)
  • With fast Internet connections that no longer require common software agents,
  • Instead, it’s the server because there are more and more applications, but there is only one external port like 80,
  • In this case, a reverse proxy is used to reverse multiple contents into one to the client

Node agent implementation

var express = require('express');
const proxy = require('http-proxy-middleware')

const app = express()
app.use(express.static(__dirname + '/'))
app.use('/api', proxy({ target: 'http://localhost:4000'.changeOrigin: false }));
module.exports = app
Copy the code

Vue implements the agent

//vue.config.js


  devServer: {
    disableHostCheck: true.compress: true.port: 5000.proxy: {
      '/api/': {
        target: 'http://localhost:4000'.// Note that only IP and port are set. Do not add any suffix address information
        changeOrigin: true.pathRewrite: { // Override the prefix of the replacement URL request
          '^/api': ' ' // Because the API does not exist in the real interface, it is recommended to remove it}}},}Copy the code

Nginx implements the proxy

server {
   listen       80;
   # server_name  www.josephxia.com;
   location / {
       root   /var/www/html;
       index  index.html index.htm;
       try_files $uri $uri/ /index.html;
   }

   location /api {
           proxy_pass  http:/ / 127.0.0.1:3000;proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }}Copy the code

Nuxt agent Settings

//nuxt.config.js
  modules: [
    '@nuxtjs/proxy' // Add proxy Settings].proxy: {"/api/": {target:"http://localhost:7001".secure:false.pathRewrite: {'^/api':""}}}Copy the code

Google Chrome directly blocks cross-domain

open -n /Applications/Google\ Chrome.app/ --args --disable-web-security  --user-data-dir=/Users/jason_pro/Documents/ChormConfig
Copy the code

Google Chrome Windows block cross domain

Google shortcut key -> Properties -> Target -> C:\Users\ XXXXXX \AppData\Local\Google\Chrome\Application\chrome.exe –disable-web-security –user-data-dir=d:\MyChromeDevUserData