var http = require('http');
var url = require('url');
var fs = require('fs');
//解析url用的模块
var querystring = require('querystring');
var server = http.createServer();
//返回当前文件的路径
var HtmlDir = __dirname + '/html/';
F14563B0-BB97-4232-9495-2E6B200C41B4.png
server.on('request',function(req,res){
var urlStr = url.parse(req.url);
switch (urlStr.pathname)
{
case '/':
//首页
sendData(HtmlDir+"index.html",req,res);
break;
case '/user':
sendData(HtmlDir+"user.html",req,res);
break;
case '/login':
sendData(HtmlDir+"login.html",req,res);
break;
case '/login/check':
sendData(HtmlDir+"login.html",req,res);
if(req.method.toUpperCase() == 'POST')
{
var str = '';
req.on('data',function(chunk){
str +=chunk;
});
req.on('end',function(){
console.log(str);
//username=%E5%95%A5%E6%89%93%E7%AE%97&password=123
console.log(querystring.parse(str));
//{ username: '啥打算', password: '123' }
});
}else
{
console.log(urlStr.query);//query:
// 'username=%E5%95%A5%E6%89%93%E7%AE%97&password=1223',
console.log(querystring.parse(urlStr.query));
//{ username: '啥打算', password: '1223' }
}
break;
default :
sendData(HtmlDir+"err.html",req,res);
break;
}
});
function sendData(file,req,res)
{
fs.readFile(file,function(err,data){
if(err){
res.writeHead(404,{
'content-type':'text/html;charset=utf-8'
});
console.log(data);
res.end('<h1>页面被吃带哦了</h1>');
}else{
res.writeHead(200,{
'content-type':'text/html;charset=utf-8'
});
res.end(data);
}
});
}
server.listen('8081','localhost');