【Vue】Vue Cli 跨域解决

Vue Cli 解决跨域问题

devServer.proxy

如果你的前端应用和后端 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://xxxxxx

所以我们这样配置:

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

devServer: {
  proxy: {
    '/api': {
      target: 'http://xxxxxx',
      ws: true,  // 代理 websocket
      secure: false,  // 是否为 https
      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
  }
}

在特定的请求我们加上/api 前缀即可

return axios.request({
  url: '/api/login',
  data,
  method: 'post',
})
posted @ 2021-02-09 17:31  [ABing]  阅读(160)  评论(0编辑  收藏  举报