var http=require("http");
var url=require("url");
var fs=require('fs');
var querystring = require('querystring');
var server=http.createServer(function(sreq,sres){
var url_parts=url.parse(sreq.url);
var pathname = url_parts.pathname;
/* //固定参数
var post_data = querystring.stringify({
func_id:'20000',
pagesize:'24',
pageindex:'0',
username:'admin',
pwd:'1234qwer',
co:'62c8ad0a15d9d1ca38d5dee762a16e01'
});*/
//node路径下的请求不转发
if(pathname.match(/^\/node/)!=null){
var realPath = 'f:/'+pathname; //文件存放路径,将此文件放在F盘node文件夹下
fs.exists(realPath, function (exists) {
if (!exists) {
sres.writeHead(404, {'Content-Type': 'text/plain'});
sres.write("404 not found.");
sres.end();
} else {
fs.readFile(realPath, "binary", function (err, file) {
if (err) {
sres.writeHead(500, {'Content-Type': 'text/plain'});
sres.end(err);
} else {
sres.writeHead(200, {'Content-Type': 'text/html'});
sres.write(file, "binary");
sres.end();
}
});
}
});
}else{
console.log("转发请求。。。。");
var opts={
host:"10.10.21.60", //请求访问的主机IP(目标主机IP)
port:8080, //请求访问的主机端口(目标主机端口)
path:url_parts.pathname,
headers:sreq.headers,
method:'POST'
};
var content = '';
//接收参数 ------ sreq.on("data",function(data){});接收html中ajax传递的参数
sreq.on("data",function(data){
var req = http.request(opts, function(res) {
res.on('data',function(body){
console.log('return');
content+=body;
}).on("end", function () {
//返回给前台
sres.writeHead(200, {'Content-Type': 'text/html'});
sres.write(content);
sres.end();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
//console.log("固定参数===="+post_data);
console.log("接收参数===="+data+"\n");
req.write(data+"\n");
req.end();
});
}
});
server.listen(8080,"127.0.0.1", function () {
console.log("开始监听"+server.address().port+"......");
});
- 安装nodeJS;
- cmd开启配置好的node服务器(即运行F盘下node文件夹中的testproxy.js文件)
- node中testproxy.js执行js监听端口,js文件需和html文件在同一个域中,放入同一文件夹下。
- 打开目标主机的后台服务器(此例子中目标主机IP为:10.10.21.60)
- 在本机浏览器内访问目标服务器,访问地址为:localhost:8080/node/login.html(项目所有html文件均和node配置文件放在同一个文件夹内,此例中为F盘的node文件夹下)
- 打开界面,直接输入账号与密码登录,跳转至相应页面