Solving Axios cross-domain problems through virtual proxy servers [Vue.js project practice: COVID-19 self-checking system]

Logo

COVID-19 Self-Detection System Web Design and Development Documents

Sylvan Ding's first project based on Vue.js. The information provided in this project is for reference only, and the accuracy, validity, timeliness and completeness of the information are not guaranteed. For more information, please see the National Health and Health Commission Commission website!
Explore the docs »

View Demo · Report Bug · Request Feature

homepage

Solving Axios cross-domain issues through virtual proxy servers

A cross-domain problem happened when a client requests data from the server. Since direct cross-domain access using axios is not feasible, we need to configure the proxy.

A proxy server requests data from another server, and then the server returns the requested data to the proxy server, and the proxy server returns the data to the client.

development environment

node 14.16.1
npm 8.18.0
view-cli 2.9.6
vue 2.5.2

solution

In the proxyTable field in the index.js file under the config folder, add the following rule:

// config/index.js

const port = 8080
const devServerPort = 8081

module.exports = {
    
    
  dev: {
    
    
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
    
    
      '/': {
    
    
        target: `http://localhost:${
      
      devServerPort}/static/mock`,
        changeOrigin: true, // override the origin of the host header
        pathRewrite: {
    
    
          '^/': '', // replace the request address in the target
        },
      },
    },
    // ...
  }
  // ...
}

Now axios will replace the beginning symbol / to http://localhost:${devServerPort}/static/mock in the request address. Make sure that we cancel baseURL configuration under development environment to avoid proxyTable being overridden.

// src/utils/request.js

const prodBaseURL = 'http://localhost:5000'

let axiosConfig = {
    
    
  timeout: 3000,
  // ...
}

// set baseURL under production environment
if (process.env.NODE_ENV === 'production') {
    
    
  axiosConfig.baseURL = prodBaseURL
}

const instance = axios.create(axiosConfig)

// ...

Please indicate the source when reprinting: ©️ Sylvan Ding 2022

Guess you like

Origin blog.csdn.net/IYXUAN/article/details/127034315