公司后台服务用的是java,前台我负责我用的是react+typescript,服务区方面就成了个大问题 不想启动在tomcat下面 也不想跨域。就想到了反向代理!
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;
};
function getLanjie(_url){
return _url.indexOf('.action')===-1&&_url.indexOf('.jpeg')===-1&&_url.indexOf('.JPG')===-1&&_url.indexOf('.xlsx')===-1&&_url.indexOf('.pdf')===-1&&_url.indexOf('.jpg')===-1&&_url.indexOf('.jsp')===-1;
}
var cookie = "";
app.use(function(req, res) {
var _url = req.url //获取请求的url
,_file
,_localPath
,_localFile
,_ext
,_stream
;
//判断文件转化
if(getLanjie(_url)){
_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.status(404).send("
");404 Not Found
}
}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("
");404 Not Found
});
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);