我已经使用jQuery来将ajax发布一些数据到nodejs web服务器。获取帖子的有效载荷
Web服务器代码收到帖子,但我不知道如何检索有效负载,并且nodejs文档网站太糟糕了。我试着将请求对象转储到调试器控制台,但我无法在那里看到数据。我如何访问帖子的有效载荷?
文档说request对象是http.IncomingMessage
一个实例,并暴露了data
事件与签名function (chunk) { }
其中一块是字符串或Buffer
,但如果你不知道在哪里,你应该如何挂钩直到这个事件,或者如何使用缓冲区,那么这不是非常有用。
我注意到在“社区”而不是“文档”链接下隐藏了第二个更具叙述性的手册。这很好。它目前不可用。这不太好。
我有人问我是否使用框架或试图做到“本地”。无知使我没有直接回答,反而使这里是现在我已经加入此
request.addListener('data', function(chunk){
console.log('got a chunk');
});
为createServer成功功能的启动代码
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/');
。它看起来像这样工作,我想这意味着成功函数在听众之前被调用。如果这是而不是正确的地方绑定然后有人请告诉我。
您是否正在使用某种类似Web的框架,或者正在尝试以“原生”方式执行此操作? – 2013-03-18 23:09:50
查看修改后的问题 – 2013-03-18 23:57:59