Objective: To resolve cross-domain access problems by configuring vuE-CLI proxies

Why cross-domains?

At present, the most popular is the front and back separated project, that is, the front-end project and the back-end interface are not under the same domain name, so there must be cross-domain behavior when the front-end project accesses the back-end interface

Note that the cross-domains we encounter are in the development environment, and the cross-domains that are actually deployed live are in the production environment

Resolve cross-domain issues in the development environment

Cross-domain development environment

The cross-domain of the development environment, that is, when the vuE-CLI scaffolding environment is developed to start services, we encounter cross-domain problems in accessing the interface, VUe-CLI for us in the local open a service, through this service can help us broker requests, solve cross-domain problems

This is the reverse proxy for vue-CLI configuration Webpack

The vuE-CLI proxy configuration is used

The vue-CLI configuration file is vue.config.js, which has the proxy options we need

module.exports = {
  devServer: {
   // Proxy configuration
    proxy: {
        // If the request address has a/API, the proxy mechanism will be triggered
        // localhost:8888/ API/ABC => proxy to another server
        // Local front end = "local back end =" proxy we send a request to another server (ok)
        // local front-end = "another server sends a request (cross-domain doesn't work)"
        '/api': {
        target: 'www.baidu.com'.// We want the address of the agent
        changeOrigin: true.// Whether cross-domain requires this value to be set to true to allow the local service to broker requests for us
         // Path overwrite
         // The default path is target+baseUrl+apiUrl
         For example, www.baidu.com/api/login, if the path of the back-end interface is the path, you do not need to write pathRewrite
        pathRewrite: {
            // Reroute localhost:8888/ API /login => www.baidu.com/api/login
            '^/api': ' ' // Suppose we want to change localhost:8888/ API /login to www.baidu.com/login}},}}}Copy the code

Note: the vue. Config. js changes need to be restarted in order to take effect

Also note that we also need to comment out the loading of the mock because mock-Server can cause an exception to the proxy service

// before: require('./mock/mock-server.js'), // annotate mock-server loadingCopy the code

Cross-domain development environment – Sample application

1. Environment variables in REQUEST

Distinguish between the underlying addresses that AXIOS requests in different environments

A development environment is actually something you develop locally or in a less demanding environment, but once it’s in production, it’s real data. Using the analogy of a bank, if you test the interfaces of the production environment in the development environment, the banking system is at great risk.

The front-end mainly distinguishes between two environments, the development environment and the production environment. The address of the request sent by the two environments is the environment variable to distinguish the environment variable

$process.env.node_env # $processCopy the code

Environment file

We can define variables in.env.development and.env.production, and the variables are automatically the values of the current environment

The base template defines the variable VUE_APP_BASE_API in the above file, which can be used as the baseURL for axios requests

We’ll notice that in the template, the two values are /dev-api and /prod-api

But our development environment proxy is/API, so it can be unified

VUE_APP_BASE_API = '/ API 'Copy the code
VUE_APP_BASE_API = '/prod-api' /prod-api = '/prod-api'Copy the code

Note in this section: We set different values for the production environment and the development environment. Later, we will configure the reverse proxy corresponding to the value when the production environment is deployed. It is entirely up to us to determine which address the reverse proxy points to, and it will not conflict with the development environment

2. Set baseUrl in the request

Const service = axios.create({// If NPM run dev is set to/API correctly/API this proxy is only configured for the development environment // If NPM run build is set to /prod-api VUE_APP_BASE_API, // set the base address timeout of the axios request base: }) // Create an instance of AXIosCopy the code

3. Encapsulate a separate login interface

src/api/user.js

export function login(data) {
  // Return an AXIos object => PROMISE
  return request({
    url: '/sys/login'.// Because all interfaces need to cross domains, all interfaces need to have/API
    method: 'post',
    data
  })
}
Copy the code

4. Configure the proxy across domains

  • The front-end code

    • Axios.post (‘/sys/login’) and baseUrl concatenation

    • (2)axios.post(‘/ API /sys/login’) path is relative path, relative to root (http://localhost:8888/)

    • (3) axios. Post (‘ http://localhost:8888/api/sys/login ‘) this path will be blocked by devSever begin with/API url

  • DevSever service agent

    • (4) Server accesshttp://ihrm-java.itheima.net/api/sys/loginAccess sends us the data

vue.config.js

 // Proxy cross-domain configuration
    proxy: {
      // When our local request has a/API, it makes a request to another server on behalf of our request address
      '/api': {
        target: 'http://ihrm-java.itheima.net/'.// Address of the cross-domain request, no API is written here
        changeOrigin: true // Cross-domain is enabled only if this value is true}}Copy the code

Cross-domain production environment (to be added)

The production environment means that we have developed the project and deployed the project to the server, without the assistance of the VUE – CLI scaffolding, we just delivered the packaged HTML + JS + CSS to the operation staff and put it on the Nginx server, so we need to use the reverse proxy of Nginx

Server {# listen 9099; Localhost server_name localhost; Localhost :9099/ API: http://baidu.com location ^~ / API {proxy_pass http://baidu.com; }}Copy the code

Note: The operation here is generally completed by operation and maintenance personnel and requires front-end operation. Here we have a brief understanding

For more on forward and reverse proxies, read the article Nginx Reverse proxies