javascript 如何在 Node JS 中做一个简单的读取 POST 数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5528081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do a simple read POST data in Node JS?
提问by user176855
I've used this code to read the querystring ?name=Jeremy ...can anyone tell me how to do this with post data? also with json?
我已经使用此代码读取查询字符串 ?name=Jeremy ...谁能告诉我如何使用发布数据执行此操作?也用json?
var http = require('http'), url = require('url');
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type":"text/plain"});
var urlObj = url.parse(request.url, true);
response.write("Hello " + urlObj.query["name"] + "!\n");
}).listen(8000);
thanks!
谢谢!
回答by yojimbo87
You have to handle dataand endevents of http.ServerRequestobject. Example:
您必须处理http.ServerRequest对象的数据和结束事件。例子:
var util = require("util"),
http = require('http'),
url = require('url'),
qs = require('querystring');
...
// this is inside path which handles your HTTP POST method request
if(request.method === "POST") {
var data = "";
request.on("data", function(chunk) {
data += chunk;
});
request.on("end", function() {
util.log("raw: " + data);
var json = qs.parse(data);
util.log("json: " + json);
});
}
Hereis an article on this topic with example (with too old version of node.js so it might not work, but the principle is the same).
这是一篇关于这个主题的文章和示例(node.js 版本太旧,所以它可能无法工作,但原理是相同的)。