nodejs 实现反向代理

陈帅2144 2016-03-13 01:26:42
公司开发新的程序我使用了typescript作为开发语言,但公司后台服务器用的却是java,我也不想使用eclipse做开发 而选用了vs code,web服务器需要用tomcat,所有文件同步就成了问题。刚开始使用了freefilesysn作为文件同步,让修改的js同步到tomcat服务器下,后来想到了代理服务器。于是便用node做了代理服务器,如果遇到action便从tomcat服务器做请求这样就可以做到静态文件不需要转移。刚开始参考了
http://www.tuicool.com/articles/JzI7vaf
但是这篇文章中写的例子无法记住session 于是我自己做了一个可以记住session的版本

/*
http-proxy
*/
var http = require('http')
,httpProxy = require('http-proxy') //http-proxy
,proxy = httpProxy.createProxyServer({xfwd:true})
,fs = require('fs')
,path = require('path');
var express = require('express');
var app = express();


var getConType = function(ext){
var contentType = '';
switch(ext){
case ".html":
contentType= "text/html";
break;
case ".js":
contentType="text/javascript";
break;
case ".css":
contentType="text/css";
break;
case ".gif":
contentType="image/gif";
break;
case ".jpg":
contentType="image/jpeg";
break;
case ".png":
contentType="image/png";
break;
case ".ico":
contentType="image/icon";
break;
default:
contentType="application/octet-stream";
}

return contentType;
};
var cookie = "";
app.use(function(req, res) {
var _url = req.url //获取请求的url
,_file
,_localPath
,_localFile
,_ext
,_stream
;
if(_url.indexOf('.action')===-1&&_url.indexOf('.jpg')===-1&&_url.indexOf('.pdf')===-1){
_file = _url.replace(/\?.*/ig,'');
_ext = path.extname(_file); // 文件扩展
//转换成本地路径
_localPath = __dirname+'/dcscloud2/WebRoot';;
_localFile = _localPath+_file;

//判断文件是否存在
if(fs.existsSync(_localFile)){//如果文件存在
res.sendfile(_localFile);
}else{//返回404错误
res.send("<h1>404 Not Found</h1>");
}
}else{
proxy.web(req, res, { target: 'http://127.0.0.1:8080/dcscloud' });
}
});
proxy.on('proxyReq', function (proxyReq, req, res) {
req.headers.cookie = cookie + req.headers.cookie
proxyReq._headers = req.headers;
return req;
});

proxy.on('error', function (proxyReq, req, res) {
res.send("<h1>404 Not Found</h1>");
});

proxy.on('proxyRes', function (proxyRes, req, res) {
var JSESSIONID = proxyRes.headers['set-cookie'];
if(JSESSIONID){
cookie = JSESSIONID;
res.setHeader('Set-Cookie',proxyRes.headers['set-cookie']);
}
});
console.log("服务已经启动!")
app.listen(80);
...全文
301 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_45636844 2019-09-16
  • 打赏
  • 举报
回复

5,655

社区成员

发帖
与我相关
我的任务
社区描述
Web开发应用服务器相关讨论专区
社区管理员
  • 应用服务器社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧