SoFunction
Updated on 2025-04-06

How to solve cross-domain problems with vue project configuration agent

Vue project configuration agent

When the front-end sends requests to the server, it often encounters cross-domain problems. So what is front-end cross-domain?

How to solve it using proxy in vue project?

1. Here we take axios request as an example

("/abc/def");
("/abc/ghi");
("/abc/jkm");

The request sent by axios is a request sent on the local server address splicing, such as http://localhost:8080/abc/def

2. If the requests sent start with /abc

Then we can configure the server proxy in proxy.

devServer: {
    proxy: {
      "/abc": {
        target: ":8081",
        changeOrigin: true,
        ws: true,
        secure: false,
      },
    },
},

"/abc":{} : The quotation marks represent the monitoring interface starting with /abc

target: After monitoring an interface starting with /abc, change the address of the previous local server in the axios request to the backend interface address. The actual request sent to the backend is the next request below

http://localhost:8080/abc/def --> :8081/abc/def

  • changeOrigin : Whether it crosses the domain
  • ws : If you want to proxy websockets, configure this parameter
  • secure : If it is an https interface, you need to configure this parameter (if it is an http interface, you can also not write this parameter)
  • pathRewrite : Replace the matching content in the request. The usage is explained in detail in Method 2 of 3, this parameter is not used above

3. Proxy multiple interfaces

http://localhost:8080/zzz/one

http://localhost:8080/xxx/two

Method 1: Monitor multiple interfaces, you can write multiple configurations in proxy: (Applicable to different target agents, you can also use this method the same way, which is a little more troublesome, and it will be more convenient for the same target method 2)

devServer: {
    proxy: {
        "/zzz": {
          target: ":8082",
          changeOrigin: true,
          ws: true,
        },
        "/xxx": {
          target: ":8083",
          changeOrigin: true,
          ws: true,
        },
    },
},

Then the actual request sent to the backend is:

:8082/zzz/one

:8083/xxx/two

Method 2: Use axios for pre-setting (for target same proxy)

// It is generally introduced in global settings, for example, to facilitate the configuration of the second line to be recognized by each axios requestimport axios from "axios";
// Just send an axios request and add the beginning of /api before the request, for example /zzz/one -> /api/zzz/one = "/api";    

After the above configuration is performed, the request sent locally will become

http://localhost:8080/api/zzz/one

http://localhost:8080/api/xxx/two

Then you can set a proxy that only listens to "/api", but you need to set the pathRewrite parameter:

devServer: {
    proxy: {
        "/api": {
            target: ":8084",
            changeOrigin: true,
            ws: true,
            pathRewrite: {
              "^/api": "",
            },
        },
    },
},

pathRewrite: Check whether there is /api in the proxy request. If so, replace /api with the content after the colon. The case is to replace it with an empty string, that is, delete /api. (^ is the content of a regular expression, meaning to limit the beginning)

  • Local request http://localhost:8080/api/zzz/one ->
  • Request after proxy: 8084/api/zzz/one ->
  • Request after setting pathRewrite: 8084/zzz/one
  • So the request that the agent actually sends to the backend after completion is: 8084/zzz/one.

1. Add/api to requests to facilitate monitoring proxy 2. Delete/api to send correct requests)

  • Note: Friends may see the right-click in the browser to check the open console, Network -> Header -> General, and the request URL in the browser still displays: 8084/api/zzz/one.
  • This is because the browser's homologous policy, the requests set by the proxy have been sent to the backend, and the requests set by the proxy have become:8084/zzz/one without /api, and they do not need to be interfered with by the request URL displayed by the browser.
  • If you really don't want to see the browser's request URL, you can use method 1.

What is cross-domain?

JavaScript homologous policy: When any of the protocol, subdomain, main domain, and port number are different, they are considered different domains.

Different domains request resources from each other, which is considered "cross-domain".

The same-origin policy requires that the source is the same to communicate normally, that is, the protocol, domain name, and port number are completely the same. **Same-origin policy restrictions: **Form submission, AJAX request, etc.

Note: Cross-domain does not mean that the request cannot be sent out. The request can be sent out. The server can receive the request and return the result normally, but the result is intercepted by the browser.

proxy proxy solves cross-domain

**Principle: **The browser prohibits cross-domain, but the server does not prohibit it. When running commands such as npm run serve locally, it actually runs a server with node. Therefore, proxyTable actually sends the request to its own server, and then forwards it to the backend server, making a layer of proxy, so there will be no cross-domain problems.

When we use the native machine to find the server for data, cross-domain problems will arise, so we use vue-cli to open a proxy server.

Configuration ()

Method 1

Advantages: Simple configuration, and send it directly to the front-end (8080) when requesting resources.

Disadvantages: Cannot configure multiple proxy, and cannot flexibly control whether requests are transferred to proxy

When a resource that does not exist in the front-end is requested, the request will be forwarded to the server (the front-end resources are preferred)

  = {
     devServer: {
             proxy: 'http://localhost:5000',
     }
 }

Method 2

Advantages: Multiple agents can be configured, and the request can be flexibly controlled whether to leave the request

Disadvantages: cumbersome configuration, prefix must be added when requesting resources

//Open the proxy server (Method 2)    devServer: {
        proxy: {
            // '/yu' is the request prefix, used to control whether to go to the proxy. When you want to go to the proxy, add this request prefix to the request prefix            '/yu': {
                target: 'http://localhost:5000',
                pathRewrite: { "^/yu": "" }, //Rewrite the path  Match paths starting with /yu all become empty strings                ws: true, // Used to support websocket                changeOrigin: true // Used to control the host value in the request header            },
            '/demo': {
                target: 'http://localhost:5001',
                pathRewrite: { "^/demo": "" },
                ws: true, // Used to support websocket                changeOrigin: true // Used to control the host value in the request header            },
        }
    }

When requested:

The request prefix must be followed by the port number

getStudents() {
      ("http://localhost:8081/yu/students").then(
        (response) => {
          ("The request succeeded", );
        },
        (error) => {
          ("The request failed", );
        }
      );
    },
    getCars() {
      ("http://localhost:8081/demo/cars").then(
        (response) => {
          ("The request succeeded", );
        },
        (error) => {
          ("The request failed", );
        }
      );
    },

-cli 2 is configured in proxyTable under the file with the path config/, which is the main configuration portal for the entire project

// The node comes with its own path tool.var path = require('path')
// It is divided into two environments, dev and production = {
  dev: {
    // After configuration, be sure to close the original server and restart npm run dev to start the project.  Otherwise it will be invalid.    proxyTable: {   // requires proxy interfaces, which can cross domain      // Start with '/api' and proxy all requests to the target server      '/api': {
            target: 'http:', // Target interface domain name            changeOrigin: true, // Whether to enable cross-domain            pathRewrite: { //It should be understood here that '/api' is used instead of the address in the target. In the following components, we directly use API when calling the interface. For example, if I want to call 'http://40.00.100:3002/user/add', and write it directly as '/api/user/add'.              '^/api': ''  // That is, /api is equivalent to http://40.00.100:3002            }
        }
     }
  }
}

Note: ‘/api’ is a match, because the prefix ‘/api’ is added to the ajax url, and the original interface does not have this prefix, so you need to rewrite the address through pathRewrite and convert the prefix ‘/api’ to ‘/’.

If the interface address itself has a common prefix such as ‘/api’, pathRewrite can be deleted.

-cli 3 creates a new file in the root directory and configures it in the object (of course there are other ways). After configuration, it will be automatically integrated with the hidden configuration

 = {
    // cli3 proxy starts to match after the specified target, not anywhere; configure pathRewrite to be used as a replacement    devServer: {
      proxy: {
        '/yourapi': {   //Proxy API, /yourapi means that requests that declare that url in Axios have started /api apply to this rule. Note that it starts with /yourapi, that is: ({url: '/yourapi/xxx/xxx'})          target: 'yourserver',   //The server's real API address, that is, the target interface that needs to be requested. The meaning of target here is: the cross-domain is because the accessed host is inconsistent with the origin in our request header, so we need to set it to be consistent. Please see the following article for details.          changeOrigin: true,    //Whether cross-domain, true is to enable proxy: a virtual server will be created locally, and then the requested data will be sent and the requested data will be received at the same time. In this way, there will be no cross-domain problem when the server and the server interact with the data.          ws: true, // Whether to enable websockets, and see if the item needs to be configured according to the actual situation          pathRewrite: { 
               '^/yourapi': 'https://I am the server/api' //Rewrite the path        // This is where most articles will not explicitly state it.        // Since we have set up a proxy, all request urls have been written as /yourapi/xxx/xxx. How do you know which server data we are requesting?        // So the meaning here is that the proxy will know that the url request starting with /yourapi should actually request there.        // 'I am the server/yourapi', the following /api is determined based on the actual request address, that is, my request url: /yourapi/test/test, and the requested after being proxy is        // https://I am the server/yourapi/test/test          } 
        }
      }
    }
  }

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.