2017-01-30 254 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