第一次发表,将自己遇到的问题,解决办法记录下来,希望能有帮助,希望多多交流。本文示例实现了简单的前后台分离。
安装nodeJS,cmd转到存放js的文件夹下,node testproxy.js启动监听。
1.简单示例
var http = require('http');
var url=require('url');
http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
var content = '';
var opt = {
host:'news.163.com',
port:'80',
method:'GET',
path:pathname
};
var req = http.request(opt, function(res) {
res.on('data',function(body){
console.log('return');
content+=body;
}).on("end", function () {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(content);
response.end();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
req.end();
}).listen(80);//监听端口80,将80端口的请求转发到news.163.com
console.log("Server runing at port: " + 80 + ".");
2.项目示例
(1)testProxy.js
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;
/* //固定参数,本示例是用的ajax请求,此处是将ajax的post参数写死,测试成功后,进一步接收参数。
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;//前台的html需放到f:/node下
fs.exists(realPath, function (exists) {
if (!exists) {
sres.writeHead(404, {'Content-Type': 'text/plain'});
sres.write("404 not found.");
sres.end(data,'utf-8');
} 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.65",//跨域访问的主机ip
port:8080,
path:url_parts.pathname,
headers:sreq.headers,
method:'POST'
};
var content = '';
sreq.on("data",function(data){//接收参数 ------ sreq.on("data",function(data){});接收html中ajax传递的参数
var req = http.request(opts, function(res) {
res.on('data',function(body){
console.log('return');
content+=body;
}).on("end", function () {
//返回给前台
if(res.headers != null&& res.headers['set-cookie'] != null){
//console.log("=======res.headers.cookie======="+res.headers.cookie);
sres.writeHead(200, {
'Content-Type': 'text/html',
'Set-Cookie': res.headers['set-cookie']
});//将cookie放到response中
}
else{
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");
if(sreq.headers.cookie != null ){
req.setHeader('Cookie',sreq.headers.cookie);
}//获取request中的cookie</span>
req.write(data+"\n");
req.end();
});
}
});
server.listen(8080,"127.0.0.1", function () {//监听端口8080
console.log("开始监听"+server.address().port+"......");
});
(2)login.html
<strong><script language="javascript" type="text/javascript">
function login(){
var code=escape($("#username").val());
var co = hex_md5($("#pwd").val());
if($("#username").val()==''){
alert('用户名格式不正确!');
return;
}
if($("#pwd").val()==''){
alert('密码不能为空!');
return;
}
$.ajax({
url : "http://localhost:8080/terminal/DataServlet", //将会转发此请求到10.10.21.65:8080/terminal/DataServlet
type : "POST",
dataType : "json",
data : {//post请求参数
func_id:20000,
pagesize:24,
pageindex:0,
username:$("#username").val(),
pwd:$("#pwd").val(),
co:co
},
success : function(data) {
//console.log(data);
alert("===success===");
if(data.success=="1"){
logindo();
}else{
if(data.err_code=="1"){
alert("登录尝试次数过多,请您"+data.locked_mins+"分钟后重新登录");
}else{
alert("登录失败,请重新登陆!");
}
}
},
error : function() {
alert("====error====");
}
});
}
function logindo(){
window.location = 'page.html';
}
</script>
</head>
<body>
<!-- Top content -->
<div class="top-content">
<div class="inner-bg">
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2 text">
<h1 style="font-family:'微软雅黑';"><strong><img src="images/zhongduan_logo.png" style="width:60px;"/>行为检测分析系统</strong></h1>
<div class="description">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-sm-offset-3 form-box">
<div class="form-top">
<div class="form-top-left">
<h3>登录进入系统</h3>
<p>请输入用户名和密码进行登录:</p>
</div>
<div class="form-top-right">
<i class="fa fa-lock"></i>
</div>
</div>
<div class="form-bottom">
<table>
<div class="form-group">
<label class="sr-only">用户名</label>
<input id="username" type="text" name="username" placeholder="用户名..." class="form-username form-control">
</div>
<div class="form-group">
<label class="sr-only" for="form-password">密 码</label>
<input id="pwd" type="password" name="form-password" placeholder="密码..." class="form-password form-control" onKeyPress="if (event.keyCode == 13) login();">
</div>
<button class="btn" style="background-color:rgb(255, 185, 0);" onClick="login();">登 录</button>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
</strong>