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 的响应结果:
devServer.proxy.target 为 nginx:8000 的响应结果:
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: