2017-01-30 3 views
1

私の知見によれば、response.end()はノードのapiドキュメントに従って、すべての応答の後に呼び出されるべきですhereNode_s内でresponse.end()が動作していない

しかし、response.end()と呼ぶと、ブラウザにhtmlファイルがロードされません。それはprintMe()機能を実行する場合は、「が、これはエラーを持っている」のテキストがブラウザに表示されます、

var http=require('http'); 
var fs=require('fs'); 

http.createServer(creatingRequest).listen(8000); 
console.log("connected to the server"); 

function printMe(response) { 

    response.writeHead(404,{"Context-Type":"text/plain"}); 
    response.write("this has errors "); 
    response.end(); 
    console.log("finished "+response.finished);//true if response ended 
    console.log("printMe"); 

} 

function creatingRequest(request,response) { 



    if ((request.url=="/") && request.method=="GET") 
    { 

    response.writeHead(200,{"context-type":"text/html"}); 
    fs.createReadStream("./index.html").pipe(response); 

    console.log("loading html"); 
    response.end(); 
    console.log("finished "+response.finished);//true if response ended 
    } 
    else 
    { 

    printMe(response); 
    } 

} 

しかし:ここ

は私のコードです。ここで

は私のindex.htmlです:

<!DOCTYPE html> 
<html> 
<head lang="en"> 
    <meta charset="UTF-8"> 
    <title></title> 
</head> 
<body> 
    Hi,this is my page 
</body> 
</html> 
+0

あなたも、あなたがページに書き込みたい場合は、あなたが 'response.send()' – Roljhon

+0

@Roljhonを使用する必要があり、あなただけの接続を終了している、あなたの応答を送信していない:私は送ってきましたレスポンスは 'response.writeHead()'メソッドをhtmlファイルとして使用していますか? – Kalanka

+0

あなたがそのようにしている場合、以下は問題を修正するでしょう – Roljhon

答えて

3

ストリームは応答に完全に読み出し/書き込みされているときは、応答を終了する必要があります。

あなたはストリーム上でendイベントを聞くことができ、それにはresp.end()を発砲することができます。

if ((request.url=="/") && request.method=="GET"){ 
    response.writeHead(200,{"context-type":"text/html"}); 
    var stream = fs.createReadStream("./index.html"); 

    stream.pipe(response); 

    stream.on('end', function(){ 
     console.log("loading html"); 
     response.end(); 
     console.log("finished "+response.finished);//true if response ended 
    }); 
} 
+0

はい、うまくいきます。しかし、この 'stream.on()'は何ですか? – Kalanka

+0

'stream.on()'はストリームオブジェクトのイベントリスナーです。ストリームがデータの読み込み/書き込みを終了すると、いつでも 'end'イベントが発生します。それは応答を終了するための適切な場所です。そうでなければ、応答へのストリームデータのパイプ処理を終了する前に応答を閉じます。これはnode.jsのデフォルトの非同期動作です –

+0

ありがとう、答えを明確にするためだけに必要です。 – Kalanka

関連する問題