jQuery を使用して、一部のデータを nodejs Web サーバーに ajax で投稿しました。
Web サーバー コードは投稿を受け取りますが、ペイロードを取得する方法がわかりません。また、nodejs ドキュメントの Web はひどいものです。リクエスト オブジェクトをデバッガ コンソールにダンプしようとしましたが、そこにデータが表示されません。投稿のペイロードにアクセスするにはどうすればよいですか?
ドキュメントには、リクエスト オブジェクトが のインスタンスであり、チャンクが文字列または のいずれかである署名付きのイベントがhttp.IncomingMessage
公開されていると記載されていますが、このイベントに接続する場所や方法、または方法がわからない場合は、 Buffer を使用すると、これはあまり役に立ちません。data
function (chunk) { }
Buffer
「ドキュメント」リンクではなく「コミュニティ」の下に、2 つ目の、より物語的なマニュアルが隠されていることに気付きました。これはいい。現在利用できません。これはあまり良くありません。
フレームワークを使用しているのか、それとも「ネイティブ」にしようとしているのかを尋ねられました。無知なため、直接回答することはできません。代わりに、ここにコードがあります
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 の成功関数の先頭に。これは、成功関数がリスナーの前に呼び出されることを意味すると思います。これがバインドする正しい場所でない場合は、誰か教えてください.