我已經使用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