在上一篇文章(
Webpack系列:在Webpack+Vue开发中如何调用tomcat的后端服务器的接口?)咱们介绍了如何将对于webpack-dev-server的数据请求转发到后端服务器上,这在大部分状况下就够用了。
而后如今问题又来了,在生产环境下接口通常采用https协议,若是咱们要把数据请求转发到生产服务器上怎么办?
首先会想是否是把上一篇博文中提到的proxyTable改为https就能够了,以下:
proxyTable: {
'/appserver/SinglePowerStation': 'https://www.yourserver.com',
'/appserver/powerStationManage': 'https://www.yourserver.com',
},
可是实际上是不行的,转发不成功。
ar connect = require('connect');
var url = require('url');
var proxy = require('proxy-middleware');
var app = connect();
app.use('/api', proxy(url.parse('https://example.com/endpoint')));
app.use('/api-string-only', proxy('https://example.com/endpoint'));
虽然官方只说能够给connect库使用,不过由于express对于middleWare的接口要求和connect相同,都是:
function (req, resp, next)
这就好办了,直接在咱们的项目中引入该模块试试就知道了,因而:
1)在项目目录下
npm install proxy-middleware --save-dev
2)将build/dev-server.js中的proxyMiddleware更名为httpProxyMiddleware,并修改代码中的全部地方:
var httpProxyMiddleware = require('http-proxy-middleware')
3)在build/dev-server.js中引入proxy-middleware
var proxyMiddleware = require('proxy-middleware')
4)删掉原来根据proxyTable建立middleware的代码
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
console.log('init proxy api, context = ' + context)
var options = proxyTable[context]
if (typeof options === 'string') {
console.log('option: ' + options)
options = { target: options }
}
app.use(proxyMiddleware(context, options))
})
5)在上述删掉的位置添加以下代码;
app.use('/appserver/initerce1', proxyMiddleware('https://www.yourserver.com/appserver/
initerce1
'))
app.use('/appserver/
initerce2
', proxyMiddleware('https://www.yourservere.com/appserver/
initerce2
'))
——————完——————