最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在Nodejs中没有工作的response.end()

运维笔记admin17浏览0评论

在Nodejs中没有工作的response.end()

在Nodejs中没有工作的response.end()

根据我的知识,response.end()应该在每次响应之后根据描述here的nodejs api documenetation进行调用。

但是当我调用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()函数,那么“this have errors”文本将出现在浏览器上。

这是我的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
   });
}
发布评论

评论列表(0)

  1. 暂无评论