根据我的知识,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