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文件夾下)
- 打開界面,直接輸入賬號與密碼登錄,跳轉至相應頁面