首页 > 代码库 > node.js-----处理POST请求
node.js-----处理POST请求
简单的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="http://www.mamicode.com/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 postDatahttp://www.mamicode.com/= ""; 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对象的返回显示给用户的数据:
node.js-----处理POST请求
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。