简单的demo,post数据,并且接受数据
requestHandlers的模块
start() : POSt表单HTML
upload : POST数据获取页面
-----requestHandlers.js
-----router.js
-----server.js
-----index.js
requestHandlers.js
/*简但的demo POST数据,并接受数据*/ /*requestHandlers.js模块*/ 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/html"}); response.write("you've sent" + postData); response.end(); } exports.start = start; exports.upload = upload;
router.js
/*routers.js 模块*/ /*通过检查给定的路径对应的请求处理程序是否存在,如果存在的话直接调用相应的函数,并返回相应是字符串*/ function route(handle,pathname,response,postData){ console.log("About to route a request for " + pathname); if(typeof handle[pathname] === 'function'){ handle[pathname](response,postData); }else{ console.log("No request handler for " + pathname); response.writeHead(404,{"Content-Type":"text/html"}); response.write("404 Not found"); response.end(); } } exports.route = route;
server.js
/*server模块*/ var http = require("http"); var url = require("url"); function start(route, handle){ function onRequest(request, response){ var postData = ""; var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + "received"); request.setEncoding("utf8"); request.addListener("data",function(postDataChunk){ postData += postDataChunk; console.log("Received POST data chunk" + postDataChunk + "."); }); request.addListener("end", function(){ route(handle, pathname, response, postData); }); } http.createServer(onRequest).listen(3000); console.log("Server has started"); } exports.start = start;
index.js
/*index模块*/ var server = require("./server"); var router = require("./router"); var requestHandlers = require("./requestHandlers"); var handle = {} //区分大小写的 handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/upload"] = requestHandlers.upload; server.start(router.route, handle);
命令行启动应用:
node index.js
浏览器输入:
http://127.0.0.1:3000/
命令行显示:
浏览器显示:
submit之后命令行显示:此时URL改变,调用/upload的处理程序。
命令行显示:
浏览器显示:response对象的返回显示给用户的数据: