tuwen.js
var optfile = require('../module/optfile.js');
var imgFile=require('../module/image.js');
var url=require('url');
var querystring = require('querystring');//post导入
module.exports={
buny:function(req,res){
//post方式接收参数
var post='';//定义一个post变量,用于暂存请求体信息
req.on('data',function(chunk){//通过req的data时间监听函数,每当接收到请求体数据,就会存储到post变量中
post += chunk;
});
req.on('end',function(){//在end事件触发后,通过querystring.parse将post解析为真正的post格式,然后向客户端返回
post = querystring.parse(post);
console.log('login:'+post['login']+'\n');
console.log('pass:'+post['pass']+'\n');
// res.write('收到参数:'+post['login']+'\n');
// res.end();
//接收到的参数返回到客户端
//闭包,回调这个函数,客户端打印程序
arr=['login','pass'];
function recall(data){
dataStr=data.toString();
for(var i=0;i<arr.length;i++){
re=new RegExp("{"+arr[i]+"}",'g');
dataStr = dataStr.replace(re,post[arr[i]]);
}
// res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
res.write(dataStr);
res.end("");//http的协议尾
}
optfile.readfile('../view/buny.html',recall)
});
},
showImg:function (req,res){
res.writeHead(200,{'Content-Type':'image/jpeg'});
imgFile.readImg('../imgs/vue.png',res);
}
}
buny.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
喜欢你
<img src="/showImg"/>
收到参数:login是{login}<br/>
密码是:{pass}
<form action="./buny" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="login"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td align="center"><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</body>
</html>
routerhtml.js
var http=require('http');
var url=require('url');
var router=require('../module/tuwen.js');
http.createServer(function(request,response){
if(request.url !== '/favicon.ico'){//清除第二次访问
console.log('访问');
var pathname=url.parse(request.url).pathname;
pathname=pathname.replace(/\//,'');//替换前面/
console.log(pathname)
router[pathname](request,response);
// response.end("");//不写会没有协议尾部,但是写了会访问俩次
}
}).listen(8007);
console.log('Server running at http://127.0.0.1:8007/')