What is cross-domain?

The same origin policy from the browser, when any protocol, domain name, or port number is different, it counts as different domains. Different domains request resources from each other, and this is called “cross domain”.

How to solve cross-domain?

The front end addresses cross-domain proxies

Let’s take VUE as an example to solve the cross-domain problem. Set up proxy with WebPack devServer in vue.config.js to avoid cross-domain

devServer:{
    port:port,
    proxy: {/ / agent/API/user/login to http://127.0.0.1:3000/user/login
        '/api/': {
        target: ` http://127.0.0.1:3000/ `.changeOrigin: true}}}Copy the code

Front-end + back-end bypasses cross-domain JSONP

The front end constructs the

Back-end solutions cross domains

The following uses Node as an examplehttp-proxy-middlewareThe middleware

const {createProxyMiddleware} = require('http-proxy-middleware')
// Proxy to http://localhost:4000 real server
app.use('/api', createProxyMiddleware({ target: 'http://localhost:4000'.changeOrigin: true }));
Copy the code

CORS cross-domain resource sharing

Principle: CORS is a W3C specification that truly addresses cross-domain issues. It allows cross-domain requests by requiring the server to examine the request and process the response header accordingly.

The specific implementation

  • Responding to a simple request: The verb is get/post/head, there is no custom request header, content-Type is one of Application/X-wwwform-urlencoded, multipart/form-data or text/plain, it is solved by adding the following response header:
Allow http://localhost:3000 to Access res.setHeader(' access-Control-allow-origin ', 'http://localhost:3000')Copy the code
  • Suppose we add a custom request header x-Token to make the request a pre-checked request

To respond to a preflight request, you need to respond to the options request (precheck request) issued by the browser and set the response header as appropriate

if (method == "OPTIONS" && url == "/api/users") {
  res.writeHead(200, {
   // indicates that the server allows http://localhost:3000 to access the API
  "Access-Control-Allow-Origin": "http://localhost:3000".// Indicates that the server allows x-token and Content-Type fields in the request
  "Access-Control-Allow-Headers": "X-Token,Content-Type".// indicates that the server allows clients to initiate requests using POST,GET, and OPTIONS methods.
  "Access-Control-Allow-Methods": "GET,POST,OPTION"
   });
  res.end();
}else if (method == "GET" && url == "/api/users") {
    res.setHeader("Content-Type"."application/json");
    res.setHeader("Access-Control-Allow-Origin"."http://localhost:3000",)
    res.end(JSON.stringify([{ name: "tom".age: 20 }]));
Copy the code

As shown, two requests are made, the first being the OPTIONS precheck request

Nginx reverse proxy

We can configure Nginx during the release phase. Let’s look at how the reverse proxy works: ** the client sends a request to the reverse proxy, which then forwards the request to the target server and returns the obtained content to the client **

The configuration is as follows:

server {
        listen       80; # to monitor80Port server_name localhost; Location / {# access the root directory, root HTML /dist; Index.html index.htm; try_files $uri $uri/ /index.html; Vue router history mode} location/API {/ / 127.0.0.1:8081; Proxy to the back-end interfaceproxy_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