javascript - 在 Nodejs 中,response.end() 不工作

标签 javascript html node.js

据我所知,根据nodejs api文档描述的here,应该在每次响应后调用response.end() .

但是当我调用 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>

最佳答案

当流完全读/写到响应时,您应该结束响应。

例如您可以监听流上的 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
   });
}

关于javascript - 在 Nodejs 中,response.end() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935775/

相关文章:

javascript - 更新 nedb 中的一行

javascript - 使用 Javascript/jQuery 动态填充下拉列表

javascript - JS : Alter Color for specific image in HTML Canvas

php - 当导航是 PHP 包含时,Bootstrap 将事件类添加到导航栏

html - 如何为响应式窄显示定义 DIV 堆栈排序

html - 嵌套列表和百分比

javascript - Firebase 使用键推送多个对象

javascript - 如何在 magento 1.8 中包含自定义 jQuery/javascript

javascript - 如何在另一个文件中正确应用路由

javascript - 如何在保留数据的同时链接 Promises?