获取post的有效载荷

我用jQuery来ajax发布一些数据到一个nodejsnetworking服务器。

Web服务器代码收到post,但我不知道如何检索有效负载,并且nodejs文档网站是可怕的。 我试着将请求对象转储到debugging器控制台,但我看不到数据。 如何访问post的有效载荷?

该文档说,请求对象是一个http.IncomingMessage的实例,并使用签名function (chunk) { }一个data事件,其中chunk可以是一个string,也可以是一个Buffer ,但是如果您不知道自己在哪里应该连接到这个事件,或如何使用一个缓冲区,那么这不是非常有用的。


我注意到,在“社区”下面隐藏了更多的叙述手册,而不是“文档”链接。 这很好。 目前无法使用。 这不太好。


我被问到我是使用框架还是试图“本地化”。 无知使我无法直接回答,所以代之以代码

 var http = require('http'); var fs = require('fs'); var sys = require('sys'); var formidable = require('formidable'); var util = require('util'); var URL = require('url'); var mimeMap = { htm : "text/html", css : "text/css", json : "application/json" }; var editTemplate = fs.readFileSync("edit.htm").toString(); http.createServer(function (request, response) { request.addListener('data', function(chunk){ console.log('got a chunk'); }); var body, token, value, mimeType; var path = URL.parse(request.url).pathname; console.log(request.method + " " + path); switch (path) { case "/getsettings": try { mimeType = "application/json"; body = fs.readFileSync("/dummy.json"); } catch(exception) { console.log(exception.text); body = exception; } //console.log(body.toString()); break; case "/setsettings": console.log(request); //dump to debug console //PROCESS POST HERE body = ""; //empty response break; case "/": path = "/default.htm"; mimeType = "text/html"; default: try { mimeType = mimeMap[path.substring(path.lastIndexOf('.') + 1)]; if (mimeType) { body = fs.readFileSync(path); } else { mimeType = "text/html"; body = "<h1>Error</h1><body>Could not resolve mime type from file extension</body>"; } } catch (exception) { mimeType = "text/html"; body = "<h1>404 - not found</h1>"; } break; } response.writeHead(200, {'Content-Type': mimeType}); response.writeHead(200, {'Cache-Control': 'no-cache'}); response.writeHead(200, {'Pragma': 'no-cache'}); response.end(body); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/'); 

现在我已经添加了这个

 request.addListener('data', function(chunk){ console.log('got a chunk'); }); 

到createServer的成功函数的开始。 它似乎是这样工作的,我认为这意味着成功函数在听众之前被调用。 如果这不是正确的地方绑定那么有人请告诉我。

在“// POST POST HERE”处添加一个req.pipe(process.stdout); 它会将输出的数据输出到控制台。

你也可以把它pipe到一个文件req.pipe(fs.createWriteStream(MYFILE)) ,甚至退出到浏览器req.pipe(res);

在这里看到一个例子: http : //runnable.com/nodejs/UTlPMl-f2W1TAABS

您也可以将自己的处理程序添加到事件,数据,错误和结束

 var body = ''; request.addListener('data', function(chunk){ console.log('got a chunk'); body += chunk; }); request.addListener('error', function(error){ console.error('got a error', error); next(err); }); request.addListener('end', function(chunk){ console.log('ended'); if (chunk) { body += chunk; } console.log('full body', body); res.end('I have your data, thanks'); }); 

呵呵,至于“本地或模块”的问题,你可以使用像express这样的模块来parsing你的身体,并填充req.body的结果(跳过addListener疼痛,甚至为你parsingformdata或json)。 请参阅http://expressjs.com/api.html#req.body