场景 vue-cli 的devServer 或者 create-react-app 中的 proxy 经常因为 网络问题,访问海外服务器 504,通过实践,找到一种比较实用的解决方案
主要解决了下面的这个报错
I Your application is running here: http://0.0.0.0:9527
[HPM] Error occurred while trying to proxy request
/v1/api/queryReportByDayCampaign?startTime=2019-07-19&endTime=2019-07-25
from 0.0.0.0:9527 to http://www.abc.com/ (ECONNRESET)
(https://nodejs.org/api/errors.html#errors_common_system_errors)
http://blog.epoos.com/2018/05/21/proxy-error/
### create-react-app
```js
// dependencies: proxy-agent、http-proxy-middleware
// reference: https://medium.com/@Pavan_/set-up-proxy-to-work-with-multiple-apis-in-create-react-app-be595a713eb2
// location: project/src/setupProxy.js(if not exist, create it)
const ProxyAgent = require('proxy-agent')
const proxy = require('http-proxy-middleware')
const ProxyAgent = require('proxy-agent')
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(proxy('/api', {
agent: new ProxyAgent('socks5://127.0.0.1:1086'),
target: 'http://abc.com/',
changeOrigin: true,
}))
}
vue cli2
// location: project/config/index.js
// dependencies: proxy-agent、
const ProxyAgent = require('proxy-agent')
proxyTable: {
'/api': {
agent: new ProxyAgent('socks5://127.0.0.1:1086'),
target: 'http://abc.com/',
changeOrigin: true,
}
},
vue cli3
// location: project/vue.config.js
// dependencies: proxy-agent
const ProxyAgent = require('proxy-agent')
module.exports = {
devServer: {
proxy: {
'/api': {
agent: new ProxyAgent('socks5://127.0.0.1:1086'),
target: 'http://api.com',
changeOrigin: true,
}
}
},
}