2017-01-30 167 views
1

根據我的知識,response.end()應該在每個響應後根據nodejs api documenetation調用它,它被描述爲herenot working response.end()in Nodejs

但是,當我打電話給response.end()它不會加載HTML文件到瀏覽器。

這裏是我的代碼:

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); 
    } 

} 

但是,如果它運行的printMe()功能,那麼「這有錯誤」文本將出現在瀏覽器中。

這裏是我的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