var express = require('express');
var proxy = require('http-proxy-middleware');
var app = express();
app.use('/api', proxy({target: 'http://10.119.168.87:4000', changeOrigin: true}));
app.listen(3000);
说明:我们利用express在3000端口启动了一个小型的服务器,利用了app.use('/api', proxy({target: 'http://10.119.168.87:4000/', changeOrigin: true}))
这句话,使发到3000端口的/api请求转发到了4000端口。即请求http://localhost:3000/api
相当于请求http://10.119.168.87:4000/api
。
安装: npm install --save-dev http-proxy-middleware
1 var proxy = require('http-proxy-middleware'); 2 3 var apiProxy = proxy('/api', {target: 'http://www.example.org'}); 4 \____/ \_____________________________/ 5 | | 6 需要转发的请求 目标服务器