第七课 nodejs请求响应

1 server.js 接收请求接收请求参数 和接收完成需要对request增加两个监听事件

var http = require('http');
var url = require('url');
function start(route,handler)
{
function onRequest(request,res)
{
var postData ="";
var pathName = url.parse(request.url).pathname;
request.setEncoding("utf8");

request.addListener("data",function(postDataChunk)
{

//接收的参数累加 因为nodejs接收参数到达一定的大小会分片发过来
postData += postDataChunk;

console.log("Received POST data chunk '"+
postDataChunk +"'.");
});

request.addListener("end",function()
{

//得到全部参数后 发给路由
route(pathName,handler, res, postData);
});
}

http.createServer(onRequest).listen(5000);
console.log('Server Started');
}

exports.start = start;

 

2 route.js

function route(pathName,handler,res,postData)
{
console.log('router user request url:'+pathName+'\n');
if(typeof handler[pathName]==='function')
{
return handler[pathName](res,postData);
}else{
console.log('No request handler found for '+pathName);
return '404';
}
}
exports.route = route;

3 requestHandler.js

var querystring = require('querystring');
//使用 response直接输出 就不会阻塞其他请求
function start(response,postData){
console.log("Request handler 'start' was called.");

var body ='<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; '+
'charset=UTF-8" />'+
'</head>'+
'<body>'+
'<form action="/upload" method="post">'+
'<textarea name="text" rows="20" cols="60"></textarea>'+
'<input type="submit" value="Submit text" />'+
'</form>'+
'</body>'+
'</html>';

response.writeHead(200,{"Content-Type":"text/html"});
response.write(body);
response.end();

}

function upload(response,postData){
console.log("Request handler 'upload' was called.");
response.writeHead(200,{"Content-Type":"text/plain"});
response.write("You've sent: "+ postData);//有特殊的编码
response.write('querystring:'+querystring.parse(postData).text);//自动解析为中文
response.end();
}

exports.start = start;
exports.upload = upload;

4 index.js

var server = require('./server');
var route = require('./route');
var requestHandlers = require('./requestHandlers');
var handle ={}
handle["/"]= requestHandlers.start;
handle["/start"]= requestHandlers.start;
handle["/upload"]= requestHandlers.upload;

server.start(route.route,handle);

//注意输出的结果

response.write("You've sent: "+ postData);//有特殊的编码
response.write('querystring:'+querystring.parse(postData).text);//自动解析为中文

posted @ 2015-09-29 21:49  3点破面  阅读(290)  评论(0编辑  收藏  举报