nodejs之处理POST请求
下面模拟的是网页登陆的过程,当我们请求一个链接时,会获得一个表单,然后再表单中填入相应的值,然后提交登陆。
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按钮提交,然后得到如下的结果:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。