«

node,express实现反向代理

emer 发布于 2019-1-7 14:20   2923 次阅读     


1.node实现反向代理


const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer();
const proxyServer = http.createServer((req, res) => {
  proxy.web(req, res, {
    target: 'http://localhost:8888',
  });
});
proxyServer.listen(8088, () => {
  console.log('proxy server is running ');
});

2.express实现



首先安装expresshttp-proxy-middlewareconnect-timeout(此模块用于处理超时):

npm install --save-dev express http-proxy-middleware connect-timeout ## 如有问题,则可以尝试使用下面的代码进行安装 npm install --save-dev express@4.16.2 http-proxy-middleware@0.17.4 connect-timeout@1.9.0


const express = require('express');
const timeout = require('connect-timeout');
const proxy = require('http-proxy-middleware');
const app = express();

// 这里从环境变量读取配置,方便命令行启动
// HOST 指目标地址
// PORT 服务端口
const { HOST = 'http://10.10.0.21:9080', PORT = '3300' } = process.env;

// 超时时间
const TIME_OUT = 30 * 1e3;

// 设置端口
app.set('port', PORT);

// 设置超时 返回超时响应
app.use(timeout(TIME_OUT));
app.use((req, res, next) => {
  if (!req.timedout) next();
});

// 静态页面
// 这里一般设置你的静态资源路径
app.use('/', express.static('static'));

// 反向代理(这里把需要进行反代的路径配置到这里即可)
// eg:将/api/test 代理到 ${HOST}/api/test
app.use(proxy('/api/test', { target: HOST }));

// 监听端口
app.listen(app.get('port'), () => {
  console.log(`server running @${app.get('port')}`);
});



const express = require('express');
const timeout = require('connect-timeout');
const proxy = require('http-proxy-middleware');
const app = express();

// 这里从环境变量读取配置,方便命令行启动
// HOST 指目标地址
// PORT 服务端口
const { HOST = 'http://127.0.0.1:9090', PORT = '4000' } = process.env;

// 超时时间
const TIME_OUT = 30 * 1e3;

// 设置端口
app.set('port', PORT);

// 设置超时 返回超时响应
app.use(timeout(TIME_OUT));
app.use((req, res, next) => {
  if (!req.timedout) next();
});

// 静态页面
// 这里一般设置你的静态资源路径
app.use('/', express.static('./'));

// 反向代理(这里把需要进行反代的路径配置到这里即可)
// eg:将/api/test 代理到 ${HOST}/api/test
app.use(proxy('/api',
 { target: HOST,
   changeOrigin:true,
   pathRewrite:{
    "^/api":"/"
   }
 }));

// 监听端口
app.listen(app.get('port'), () => {
  console.log(`server running @${app.get('port')}`);
});

/*cookie登录*/


import express,{Request,Response,NextFunction} from 'express'
const timeout = require('connect-timeout');
const {createProxyMiddleware } = require('http-proxy-middleware');

let app=express();

interface baseConfig{
    proxy_url:string,
    local_port:number,
    timeout:number
}

interface Ex_Request extends Request{
  timedout?:string | undefined
}

let HttpConfig:baseConfig={
    proxy_url:'http://oa.vstecs.com',
    local_port:9000,
    timeout:30 * 1e3
}

//设置端口
app.set('port', HttpConfig.local_port);

// 设置超时 返回超时响应
app.use(timeout(HttpConfig.timeout));
app.use((req:Ex_Request, res:Response, next:NextFunction) => {

  if (!req.timedout) next();
});

// 静态页面
// 这里一般设置你的静态资源路径
app.use('/', express.static('./'));

/*
    反向代理配置
    简单赘述:就是本地访问 /workflow 这个接口,把所有请求反向代理到服务器,但由于本地html未登陆,所以代理处加了个登陆的cookie,很简单
*/
let options={
  target:HttpConfig.proxy_url,
  changeOrigin: true, // needed for virtual hosted sites
  ws: true,
  onProxyReq(proxyReq) {
    //本地由于没有cookie,所以这里设置了cookie,发送给后台,这里可以设置发送给后台的headers,自己研究,更多设置请查询https://www.npmjs.com/package/http-proxy-middleware
    proxyReq.setHeader('Cookie', 'cid_yuchen.gu_vstecs.com=Tm5rd2RUVmpOR2d6WlRSdU1DNHdaemwx; cid_yuchen.gu_vstecs.com=Tm5rd2RUVmpOR2d6WlRSdU1DNHdaemwx; ecology_JSessionId=abcfALVsOuPqU--tubvxx; testBanCookie=test; loginfileweaver=%2Fwui%2Ftheme%2Fecology8%2Fpage%2Flogin.jsp%3FtemplateId%3D21%26logintype%3D1%26gopage%3D; languageidweaver=7; coworkLayout=1; yili_userid=ning.li2; yili_token=c3c5b5c6-6685-4f99-a9ce-fb1a5f0959a4; loginidweaver=3216; logincookiecheck=1605596698219+B66D490F2068141D536C6FE44F6D7648; sessionkey=225d8b0e-acfd-4bd1-864b-767e3aca54b4');
   }
}
 app.use('/workflow*',createProxyMiddleware(options))

// 监听端口
app.listen(HttpConfig.local_port, () => {
  console.log(`server running @${HttpConfig.local_port}`);
});