14

こんにちは皆さん、私は今日 node.js の学習を始めたばかりで、インターネット上で多くのものを検索してから、node.js でコーディングしてみます。これら 2 つのコードを使用して同じ結果を表示しますが、最後のコードはブラウザにエラーを表示します「ページが見つかりません」のようなものです。理由を教えてください。

// JScript source code
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

これは機能していますが、

// Include http module.
var http = require("http");

// Create the server. Function passed as parameter is called on every request made.
// request variable holds all request parameters
// response variable allows you to do anything with response sent to the client.
http.createServer(function (request, response) {
   // Attach listener on end event.
   // This event is called when client sent all data and is waiting for response.
   request.on("end", function () {
      // Write headers to the response.
      // 200 is HTTP status code (this one means success)
      // Second parameter holds header fields in object
      // We are sending plain text, so Content-Type should be text/plain
      response.writeHead(200, {
         'Content-Type': 'text/plain'
      });
      // Send data and end response.
      response.end('Hello HTTP!');
   });

}).listen(1337, "127.0.0.1");

これは機能していません

なんで?

機能していない最後のリンク http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/ すべての回答に感謝しますが、問題についてはまだ理解していません. 機能していない最後のものは、request.on だけですか?

4

2 に答える 2

13

requestは、インターフェイスhttp.IncomingMessageを実装する のインスタンスです。stream.Readable

http://nodejs.org/api/stream.html#stream_event_endのドキュメントは次のように述べています。

イベント:「終了」

このイベントは、それ以上データが提供されなくなると発生します。

データが完全に消費されない限り、終了イベントは発生しないことに注意してください。これは、フロー モードに切り替えるかread()、最後まで繰り返し呼び出すことで実行できます。

var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
  console.log('got %d bytes of data', chunk.length);
})
readable.on('end', function() {
  console.log('there will be no more data.');
});

したがって、あなたの場合、どちらも使用しないか、イベントread()をサブスクライブしないためdataendイベントは決して発生しません。

追加する

 request.on("data",function() {}) // a noop

イベントリスナー内でコードを機能させる可能性があります。

リクエスト オブジェクトをストリームとして使用する必要があるのは、HTTP リクエストに本文がある場合のみであることに注意してください。たとえば、PUT および POST 要求の場合。それ以外の場合は、リクエストが既に終了していると見なして、データを送信するだけです。

投稿したコードが他のサイトからそのまま引用されている場合、このコード例は Node 0.8 に基づいている可能性があります。Node 0.10 では、ストリームの動作に変更がありました。

http://blog.nodejs.org/2012/12/20/streams2/より

警告: 'data' イベント ハンドラーを追加したり、resume() を呼び出したりしないと、永久に一時停止状態になり、'end' を発行することはありません。したがって、投稿したコードは Node 0.8.x では機能しますが、Node 0.10.x では機能しません。

于 2013-10-14T19:17:55.090 に答える