Docker 环境下 Vue dev 跨域的深刻回忆

一直报错:Proxy error: Could not proxy request /authorizations from localhost:8080 to localhost:8000 (ECONNREFUSED).

ECONNREFUSED (Connection refused) 说是连接不活动的主机

终于 Google 到了问题所在,我居然又给忘记了 Docker容器和桥接网络的区别,上次第一次接触 Docker 时也遇到过,但给忘了。没完全理解这概念
传送门:stackoverflow 的答案

VUE 代码

.env.development:

# base api
VUE_APP_BASE_API = '/api'

vue.config.js:

devServer: {
    proxy: {
      [process.env.VUE_APP_BASE_API]: {
        target: 'http://nginx:8000', // 这样才能正确访问到
        // target: 'http://localhost:8000', 这是错误的代码,连接不到 后台Api接口 的 nginx 容器
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      }
    }
  },

Docker nginx 配置:

server {
    listen 8000; # 端口为 8000

    server_name fate-shop.com;
    root /var/www/shop/public;    # 这是后台 API 
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }
    .
    .
    .
}

请求示例代码

例如登录的后台 API 为 http://fate-shop.com/authorizations

// /api 意思为 proxy.pathRewrite 当请求地址有 /api 时转为空字符串
// 这里实际就是请求了  http://fate-shop.com/authorizations
axios.post('/api/authorizations', {
    username: 'Fate',
    password: '123456'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

devServer.proxy.target 为 localhost:8000 的响应结果:

Docker 环境下 Vue 跨域的深刻回忆

Docker 环境下 Vue 跨域的深刻回忆

devServer.proxy.target 为 nginx:8000 的响应结果:

Docker 环境下 Vue 跨域的深刻回忆

Docker 环境下 Vue 跨域的深刻回忆

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 3

俺也一样

2年前 评论
wonderfate (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!