本文涉及四个文件:
- index.js 调度和设置
- requestHandlers 页面输出
- server.js 服务器启动
- router.js 路由逻辑
index.js
//index.js(设置路由并调用server启动服务器) var server = require("./server"), router = require("./router"), requestHandlers = require("./requestHandlers"); var handle = {}; handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/sb"] = requestHandlers.sb; server.start(router.route, handle);
requestHandlers.js
//requestHandlers.js(页面函数) var querystring = require("querystring"); function start(response) { var body = '<html>' + '<head>' + '<meta http-equiv="Content-Type" content="text/html; ' + 'charset=UTF-8" />' + '</head>' + '<body>' + '<form action="/sb" method="post">' + '<input type="text" name="text"/>' + '<input type="submit" value="Submit text" />' + '</form>' + '</body>' + '</html>'; response.writeHead(200, { "Content-Type": "text/html" }); response.write(body); response.end(); } function sb(response, postData) { response.writeHead(200, { "Content-Type": "text/plain" }); response.write(querystring.parse(postData).text); response.end(); } exports.start = start; exports.sb = sb;
router.js
//router.js(路由逻辑) function route(handle, pathname, response, postData) { console.log("来自" + pathname+"的请求"); if (typeof handle[pathname] === "function") { handle[pathname](response, postData); } else { console.log("未发现来自" + pathname+"的请求"); response.writeHead(404, { "Content-Type": "text/plain" }); response.write("404 Not found"); response.end(); } }; exports.route = route;
server.js
//server.js(服务器启动函数) var http = require("http"), url = require("url"); function start(route, handle) { function onRequest(request, response) { var postData = ""; var pathname = url.parse(request.url).pathname; console.log("来自" + pathname + "的请求已接收"); request.setEncoding("utf8"); request.addListener("data", function (postDataChunk) { postData += postDataChunk; }); request.addListener("end", function () { route(handle, pathname, response, postData); }) } http.createServer(onRequest).listen(3000); console.log("服务器已启动"); } exports.start = start;