1.打开webstorm,新建project,新建index.js。
2.输入地址localhost:1337/ 出现结果如下:
3.输入username和password,点击提交结果如下图:
index.js代码如下:
var http = require("http");
var server = http.createServer();
var querystring = require("querystring");
var firstpage=function(res){
res.writeHead(200,{"Content-Type":"text/html"});
var html = '<html><body>'+
'<form action="/login" method="post">'+
'<meta http-equiv="Content-Type" content="text/html;' +
'charset=UTF-8" />'+
'name:<input type="text" name="name"> </br>'+
'password:<input type="password" name="pwd"></br>'+
'<input type="submit" value="提交">'+
'</form>'+
'</body></html>';
res.end(html);
}
var login=function(req,res){
console.log("function login");
var info="";
req.addListener("data",function(chunk){
info += chunk;
})
req.addListener("end",function(){
info = querystring.parse(info);
if(info.name == "a" && info.pwd =="1"){
res.end("login success username:" + info.name+" password:"+info.pwd);
}else{
res.end("login failed username:" + info.name+" password:"+info.pwd);
}
})
}
var requestFunction =function(req,res){
console.log("requestFunction");
if(req.url=="/"){
return firstpage(res);
}
if(req.url=="/login"){
if(req.method!="POST"){
return;
}
return login(req,res);
}
}
server.on("request",requestFunction);
server.listen(1337);
console.log("sever is running at localhost:1337");