从表格获取发布的数据

这里是一个HTML表单,它张贴:

<html> <body> <h1>Home Html Page</h1> <a href="/Product/Index">Go To Product</a> <hr/> <form action="/Home/Index" method="POST" name="form1"> Enter Text: <input type="text" id="txtInput"/> <button id="btnPost">Post Data</button> </form> </body> </html> 

这里是应该获得发布数据的JavaScript代码:

 function Server(req, resp) { if (req.method == 'POST') { var chunk = ''; req.on('data', function (data) { chunk += data; }); req.on('end', function () { console.log(chunk + "<-Posted Data Test"); }); }' ... resp.write(...); resp.end(); } 

你可以帮我吗? 我是nodejs中的新手,那么你能告诉我一个例子吗?

你必须在你的<input>元素上指定一个name ,像这样:

 <input name="txtInput" type="text" id="txtInput"> 

只有name设置的那些被张贴。

例:

 var http=require('http'); var util=require('util'); var querystring=require('querystring'); var server=http.createServer(function(req,res){ if (req.method=='GET'){ res.end('<form action="/Home/Index" method="POST" name="form1">Enter Text:<input name="txtInput" type="text" id="txtInput"/><button type="submit" id="btnPost">Post Data</button></form></body></html>'); }else{ var chunk = ''; req.on('data', function (data) { chunk += data; }); req.on('end', function () { console.log(chunk + "<-Posted Data Test"); res.end(util.inspect(querystring.parse(chunk))); }); } }).listen(8080); 

要parsing表单数据,只需使用querystring.parse(str,[sep],[eq]) (如上例所示)

例:

 querystring.parse('foo=bar&baz=qux&baz=quux&corge') // returns { foo: 'bar', baz: ['qux', 'quux'], corge: '' }