Turn on the proxy server to solve cross-domain problems

When I was studying the Ajax course in Shang Silicon Valley, I encountered a cross-domain problem for the first time – Access to XMLHttpRequest at 'http://localhost:5000/students' from origin 'http://localhost:8080' has been blocked by CORS Policy: No 'Access-Control-Allow-Origin' header is present on the requested resource error, at that time it was solved by setting the header information - setting the value of the Access-Control-Allow-Origin header information to "*" Yes, and this article mainly solves the cross-domain problem by turning on the proxy server

report error

To simulate a scene, we get the desired data through axios

<template>
  <div>
    <button @click='getStudents'>获取学生信息</button>
  </div>
</template>

<script>
import axios from 'axios'
export default {
    
    
  name: 'App',
  methods: {
    
    
    getStudents() {
    
    
      axios.get('http://localhost:5000/students')		//获取数据的网址
        .then(
          response => {
    
    
            console.log('请求成功' + response.data);
          },
          erro => {
    
    
            console.log('请求失败' + erro.message);
          }
        )
    }
  }
}
</script>

In the browser, the information is obtained by clicking the button, but an error is reported in the console:Access to XMLHttpRequest at 'http://localhost:5000/students' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

insert image description here

This is because we have crossed domains and violated the same-origin policy (the "protocol name + host name + port number" are the same).

Think about it carefully, when we run the code, the page with the port number of 8080 is displayed, and the port number of the page we need to access data is 5000, which shows that we have cross-domain

insert image description here

solution

Requests can be forwarded using a proxy server to avoid cross domain issues due to different origins. For example, in the application, we can send the request to the proxy server, the proxy server will send the request to the target site, and then return the response to the application

insert image description here

Check the official documentation, there is such a description in the documentation

If your front-end application and back-end API server are not running on the same host, you need to proxy API requests to the API server in the development environment. This question vue.config.jsis devServer.proxyconfigurable via the option in .

devServer.proxyCan be a string pointing to the development environment API server:

We need to enable the proxy server, just add the devServer configuration in the configuration file (every time you modify the information in the configuration, you need to restart the scaffolding: node run server)

const {
    
     defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
    
    
  pages: {
    
    
    index: {
    
    
      //入口
      entry: 'src/main.js',
    }
  },
  transpileDependencies: true,
  lintOnSave: false,   //关闭语法检查

  //开启代理服务器
  devServer: {
    
    
    proxy: 'http://localhost:5000'	//指向的是需要数据的网络端口号
  }
})

At the same time, the address of our axios request data points to the proxy server

insert image description here

data request successful

insert image description here

Configure multiple proxies

When accessing multiple services, we need to configure multiple proxy servers.

Specify a prefix in this machine (ps: the prefix of this machine is a prefix that ignores the protocol name, host number, and port number).

<template>
  <div>
    <button @click='getStudents'>获取学生信息</button>
    <button @click='getCars'>获取汽车信息</button>
  </div>
</template>

<script>
import axios from 'axios'
export default {
    
    
  name: 'App',
  methods: {
    
    
    getStudents() {
    
    
      axios.get('http://localhost:8080/msg1/students')
        .then(
          response => {
    
    
            console.log('请求成功', response.data);
          },
          erro => {
    
    
            console.log('请求失败', erro.message);
          }
        )
    },
    getCars() {
    
    
      axios.get('http://localhost:8080/msg2/cars')
        .then(
          response => {
    
    
            console.log('请求成功', response.data);
          },
          erro => {
    
    
            console.log('请求失败', erro.message);
          }
        )
    },
  }
}
</script>

In vue.config.js, we add multiple proxies. The proxy server configures the prefix so that the corresponding data can be forwarded. The proxy server also needs to configure pathRewrite to rewrite the path. After clearing the prefix, go to the target server to find the data. If the prefix is ​​not cleared, the data cannot be found on the target server

vue.config.js:

const {
    
     defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
    
    
  pages: {
    
    
    index: {
    
    
      //入口
      entry: 'src/main.js',
    }
  },
  transpileDependencies: true,
  lintOnSave: false,   //关闭语法检查

  //开启代理服务器
  devServer: {
    
    
    proxy: {
    
    
      '/msg1': {
    
    
        target: 'http://localhost:5000',  //代理目标的基础路径
        pathRewrite: {
    
     '^/msg1': '' },  //一定要路径重写,不然
        ws: true,
        changeOrigin: true
      },
      '/msg2': {
    
    
        target: 'http://localhost:5001',
        pathRewrite: {
    
     '^/msg2': '' },  
      }
    }
  }
})

Guess you like

Origin blog.csdn.net/cy6661/article/details/129767422