//http://www.nodebeginner.org/index-zh-cn.html#how-our-server-handles-requests 按照这个页面的例子写的,留作笔记
//index.js
var server = require('./server'); var route = require('./routes'); var requestHandlers = require("./requestHanlders"); var handle = {}; handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/upload"] = requestHandlers.upload; handle["/show"] = requestHandlers.show; server.start( route.route ,handle)
//server.js 基本的逻辑都在这边
var http = require('http'); var url = require('url'); function start( route, handle ){ http.createServer( function(request, response){ var pathname = url.parse( request.url).pathname; console.log( pathname ); var postData = ""; /* request.setEncoding("utf8"); request.addEventListener('data',function(chunk){ postData += chunk; }); request.addEventListener('end',function(){ route(handle, pathname, response ,postData) }); */ request.setEncoding("utf8"); //addEventListener ? addListener request.addListener("data", function(postDataChunk) { postData += postDataChunk; console.log("Received POST data chunk '"+ postDataChunk + "'."); }); request.addListener("end", function() { route(handle, pathname, response, postData); }); //route( handle ,pathname ,response); /* response.writeHead( 200, { "Content-Type" : "text/plain" } ); response.write(data); response.end(); console.log(' server is open'); */ } ).listen(8000); }; exports.start = start
//传数据到route文件
function route( handle, pathname ,response, postData){ console.log( "route a " + pathname ); if( typeof handle[pathname] === 'function'){ return handle[pathname]( response ,postData ); }else{ console.log('no Request') return "404 NOT FOUND" } }; exports.route = route;
//展示结果页面的主要业务神马的
var querystring = require("querystring"); var fs = require("fs"); function start( response ,postData){ console.log("request handler start") 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.writeHead(200, {"Content-Type": "text/plain"}); response.write(body); response.end(); }; function upload( response ,postData){ console.log("request handler upload"); console.log( postData ) response.writeHead("200",{ "Content-Type" : "text/html" }); response.write( querystring.parse(postData).text ); response.end() }; function show(response, postData){ console.log('request img'); fs.readFile('./1.png','binary',function(err, data){ if(err){ response.writeHead(200,{ "Content-Type" : "text/html" }); response.write('err'); response.end(); }else{ response.writeHead(200,{ "Content-Type" : "image/png" //"Content-Type" : "image/png" }); response.write(data,'binary'); response.end(); } }) } exports.start = start; exports.upload = upload; exports.show = show;