这了总结一下用 vue+webpack 开发中可能遇到的各种 proxy 问题. 希望能帮助到各位有需要的人.
首先环境分为两个大类:
你的开发机已经处于外网环境.
你的开发机处于公司内网 (behind a corporate proxy), 浏览器通过代理来上外网.
其次, 两种地方使用代理:
webpack devServer 使用代理.
axios 使用代理.
现在, 在你用 webpack devServer 开始的时候, 你有一个 API, 比如:
- var data_api = '/api/getdata.php'; // 这个 API 需要对应到下面这个外网
- // http://a.b.c/getdata.php 这个接口.
你使用这种相对路径请求数据时, 明显需要在 devServer 上配置转发 proxy 咯, 如下:
- '/api': {
- target: 'http://a.b.c',
- secure:false,
- pathRewrite: {'^/api':''},
- changeOrigin: true,
- }
但是, 当你的机器不是出于外网, 而是 behind a corporate proxy 时,,, 那你就要配置 proxy 了,,, 可如下:
- const HttpProxyAgent = require('http-proxy-agent'); // 安装一下这个包
- const proxyServer = 'http://corporate.proxy:8080'; // 这个你是公司的 proxy
- ...
- '/api': {
- target: 'http://a.b.c',
- secure:false,
- pathRewrite: {'^/api':''},
- agent:new HttpProxyAgent(proxyServer),
- }
搞定.
如果你用 axios 时, 不想借助 devServer proxy 转发, 想直接用外部的 http 地址, 比如:
var data_api = 'http://a.b.c/getdata.php'; // 我想直接用 axios 访问这个外部接口.
如果你电脑在外网, 那么直接用即可.
如果在内外, 那么就要配置 proxy,,,, 这时, proxy 需要配置在 axios 上面, 而不是 devServer 了.
- axios({
- method:'get',
- url: 'http://a.b.c/getdata.php',
- responseType:'stream',
- proxy: {
- host: 'corporate.proxy.com',
- port: 8080,
- }
- })
可以工作.
但是, 如果 data_api 的 url 是 https 的, 抱歉, 上面还是不行.
解决办法: 用 axios-https-proxy-fix 这个 axios.
- //------------file request.JS------------
- //const axios = require('axios');
- import axios from 'axios-https-proxy-fix'; // 这个插件可以代理访问 https 网站. https://github.com/axios/axios/issues/925
- const axios_proxy = axios.create({
- withCredentials:false, // 跨域
- proxy: {
- host: 'corporate.proxy.com',
- port: 8080,
- //auth: {
- // username: 'mikeymike',
- // password: 'rapunz3l'
- //}
- }
- });
- export default {
- 'axios_proxy': axios_proxy,
- }
可以参考: Axio behind proxy:
https://github.com/axios/axios/issues/1679
来源: https://www.qcloud.com/developer/article/1361328