码迷,mamicode.com
首页 > Web开发 > 详细

nodejs之处理POST请求

时间:2015-03-19 22:06:11      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:nodejs


下面模拟的是网页登陆的过程,当我们请求一个链接时,会获得一个表单,然后再表单中填入相应的值,然后提交登陆。


var http = require('http');
var querystring = require('querystring');
http.createServer(function (request, response) {
	var responseString = '';
	response.writeHead(200, {'content-type': 'text/html'});
 
	// 如果是get请求
	var postData = "";
	if (request.method == "GET") {
		responseString = '<!doctype html><html lang="en">		<head><meta charset="UTF-8" />			<title>Document</title>		</head>		<body>			<form action="/" method="post">				<input type="text" name="name" value="xulidong" />				<input type="text" name="password" value="123456" />				<input type="text" name="code" value="abc123" />				<input type="submit" value="submit" />			</form>		</body>		</html>';
 
		response.write(responseString);
 
		response.end();
	} else if (request.method == "POST") {
		request.setEncoding("utf8");
		
		request.addListener("data", function (postDataChunk) {
			postData += postDataChunk;
		});
 
		request.addListener("end", function () {
			var objectPostData = querystring.parse(postData);
			for (var i in objectPostData) {
				responseString += i + " => " + objectPostData[i] + "<br>";
			}
			response.write(responseString);
			response.end();
		});
	}
}).listen(8080, '192.168.33.98');

打开浏览器输入:http://192.168.33.98:8080/,192.168.33.98是我电脑的IP,会得到如图的网页:

技术分享

这个网页是我们在处理GET请求的代码中生成的,默认都填入的相应的值,我们可以修改或者直接点击submit按钮提交,然后得到如下的结果:

技术分享







nodejs之处理POST请求

标签:nodejs

原文地址:http://blog.csdn.net/xufeng0991/article/details/44464265

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!