vue如何实现代理,并解决跨域?

1、简单配置

module.exports = {
  devServer: {
    // 配置服务器地址
    proxy: 'http://localhost:4000'
  }
}

优缺点:

缺点:
        1、如果vue项目中public文件夹中默认有的资源,代理服务器会直接从public文件夹中寻找
        2、只能配置一个代理,无法多代理配置
优点:
        1、配置简单

2、复杂配置

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        // 放服务器地址  
        target: 'http://localhost:4000',
        //开启websocket服务,默认为true
        ws: true, 
        /*改变服务器来源,
          假设服务器端口号为http://81.24.56.211:4000,则它也变为http://81.24.56.211:4000
          目的就是为了欺骗服务器,便于代理服务器直接访问到服务器的地址
        **/
        changeOrigin: true,
        // 用于修改路径配置
        pathRewrite:{'^/api':''}
      },
      '/foo': {
        // 放其他额服务器地址
        target: '<other_url>'
      }
    }
  }
}

2.1 使用pathRewrite的意义

假设我们需要访问服务器上“/students”请求,则有

// 假设我们有这样一个请求
axios.get('http://localhost:4000/api/students').then(
    success=>{
        console.log("成功")
    },
    error=>{
        console.log("失败")
    }
)

此时我们请求的是服务器上的/api/students路径,这就不太对了,因此我们需要在配置的时候将/api默认给替换掉,所以我们有pathRewrite这样一个配置项