Vue 配置代理(Day37)

22 阅读1分钟

配置代理

方法一

在vue.config.js中添加配置

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

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可

  2. 缺点:

    1. 不能配置多个代理
    2. 不能灵活控制是否启用代理
  3. 工作方式:按照上述方式配置后,当请求前端不存在的资源时,该请求被转发给服务器;当前端存在该资源时,不转发请求,直接请求前端已有资源

App组件

<button @click="getStudentsInfo">获取学生信息</button>
import axios from "axios";
    methods:{
        getStudentsInfo(){
            axios.get('http://localhost:8080/students').then(
                response=>{
                    console.log('请求成功',response.data)
                },
                error=>{
                    console.log('请求失败',error.message)
                }
            )
        }
    }

方法二

编写vue.config.js中配置代理的具体规则

  devServer: {
    proxy: {
      // /api 请求前缀
      '/api': {
        target: 'http://localhost:5000',
        // 路径重写
        pathRewrite:{'^/api':''},
        // 用于支持websocket 不配置默认为true
        ws: true,
        //用于控制请求头中的host值 不配置默认为true
        changeOrigin: true
      },
      '/foo': {
        target: 'http://localhost:5001',
        pathRewrite:{'^/foo':''},
      }
    }
  }

注:

changeOrigin为true时:服务器请求头的host为:localhost:5000

changeOrigin为false时:服务器请求头的host为:localhost:8080

说明:

  1. 优点:可配置多个代理且可灵活控制请求是否使用代理
  2. 缺点:配置略繁琐,资源请求时必须添加前缀

App组件

<button @click="getStudentsInfo">获取学生信息</button>
<button @click="getCarsInfo">获取汽车信息</button>
import axios from "axios";   
   methods:{
        getStudentsInfo(){
            axios.get('http://localhost:8080/api/students').then(
                response=>{
                    console.log('请求成功',response.data)
                },
                error=>{
                    console.log('请求失败',error.message)
                }
            )
        },
        getCarsInfo(){
            axios.get('http://localhost:8080/foo/cars').then(
                response=>{
                    console.log('请求成功',response.data)
                },
                error=>{
                    console.log('请求失败',error.message)
                }
            )
        }
    }