3

jQuery を使用して、一部のデータを nodejs Web サーバーに ajax で投稿しました。

Web サーバー コードは投稿を受け取りますが、ペイロードを取得する方法がわかりません。また、nodejs ドキュメントの Web はひどいものです。リクエスト オブジェクトをデバッガ コンソールにダンプしようとしましたが、そこにデータが表示されません。投稿のペイロードにアクセスするにはどうすればよいですか?

ドキュメントには、リクエスト オブジェクトが のインスタンスであり、チャンクが文字列または のいずれかである署名付きのイベントがhttp.IncomingMessage公開されていると記載されていますが、このイベントに接続する場所や方法、または方法がわからない場合は、 Buffer を使用すると、これはあまり役に立ちません。datafunction (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 の成功関数の先頭に。これは、成功関数がリスナーの前に呼び出されることを意味すると思います。これがバインドする正しい場所でない場合は、誰か教えてください.

4

1 に答える 1

3

「//PROCESS POST HERE」に a を追加するreq.pipe(process.stdout);と、投稿データがコンソールに出力されます。

ファイルにパイプし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');
});

ああ、「ネイティブまたはモジュール」の質問に関しては、ボディを解析し、req.bodyに結果を入力するexpressのようなモジュールを使用できます(addListenerの痛みをスキップし、formdataまたはjsonを解析します)。http://expressjs.com/api.html#req.bodyを参照してください

于 2013-03-19T01:16:18.963 に答える