Vue-cli3 解决跨域问题
阅读原文时间:2021年04月20日阅读:1

devServer.proxy

  • Type: string | Object

    如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。

    devServer.proxy 可以是一个指向开发环境 API 服务器的字符串:

    module.exports = {
      devServer: {
        proxy: 'http://localhost:4000'
      }
    }

    这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:4000

    如果你想要更多的代理控制行为,也可以使用一个 path: options 成对的对象。完整的选项可以查阅 https://cli.vuejs.org/zh/config/#devserver-proxy

我们本地的dev-server url为http://localhost:8080,而我们的接口服务器为http://localhost:8081

所以我们这样配置:

vue.config.js中,增加下面一段代码

devServer: {
  proxy: {
    '/api': {
      target: 'http://localhost:8081',
      ws: true,
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''  //通过pathRewrite重写地址,将前缀/api转为/
      }
    }
  }
}

我们对接口的请求都是用api作为前缀,所以统一在axios.js的baseUrl中处理:

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl + '/api'
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }

这样对接口的请求就全部代理到8081的服务器上了,如果不想统一处理,那么baseUrl不用改,在特定的请求我们加上/api前缀即可,如下

return axios.request({
  url: '/api/login',
  data,
  method: 'post'
}),大家根据实际情况处理,如有疑问欢迎咨询

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章