根據我的知識,response.end()
應該在每個響應後根據nodejs api documenetation調用它,它被描述爲here。not 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>
你甚至沒有送你的迴應,你僅僅結束的連接,如果你想要寫的頁面,你應該使用'response.send()' – Roljhon
@Roljhon:我有送使用'response.writeHead()'方法作爲html文件的響應,不是嗎? – Kalanka
如果你這樣做,下面的問題將糾正 – Roljhon