Vue 前端接口跨域,本地 Nginx 代理配置

3,772 阅读1分钟
  • 在本地开发 Vue 的时候,我们可以通过 vue.config.js 配置 devServer

  • 其实服务器那边都是有配置代理的,只是我们本地平常不是特殊情况只需要通过 vue.config.js 配置 devServer 即可。

  • 但是当我们需要 原生 html 嵌入 Vue 的时候或者我们不通过 vue.config.js 配置 devServer的时候,我们就需要安装一下本地 Nginx 配置代理了。

  • 下载安装 Nginx 安装之后,启动 Nginx,然后找到 nginx.conf,在我们配置的虚拟主机里面添加代理 proxy_pass

  • nginx.conf,添加代理之后,$ nginx -s reload 刷新配置。

    server {
      # 监听端口
      listen 8080;
      # 主机名称
      server_name localhost;
      # 根目录
      root /usr/local/var/dzm;
      # 匹配协议
      location / {
          index index.html;
      }
      // 监听包含 /api/ 的链接
      location /api/ {
          // 匹配到后转发到这个域名地址
          proxy_pass http://api.test.com/;
      }
    }
    
  • Vue 代码中使用

    // Vue 生命周期方法
    mounted () {
      axios({
        url: 'http://localhost:8080/api/union/center/pageinfo',
        method: 'get',
        headers: {
          'X-Token': 'slnZOg9VrV8Xo8i5IVudlvRLgmBBlzUTNRMIn6f5EqbkFVnkPmMOJJf1pjN9'
        }
      })
      .then(res => {
        console.log(res)
      })
      .catch(err => {
        console.error(err)
      })
    }
    

    当然在使用 axios 的时候可以封装一下,将前面 http://localhost:8080 封装成 baseURL,将 headers 封装到公共配置里面。

    但是需要注意的就是 /api/ 这一段一定要跟着 url 走,不要将它也配置到公用的 baseURL 里面去,不然会请求失败。

    相当于 url: '/api/union/center/pageinfo'axios 的公用 baseURL: 'http://localhost:8080',这样配置即可。