【问题标题】:Using http.request generates error使用 http.request 会产生错误
【发布时间】:2014-12-30 03:02:15
【问题描述】:

我一直在使用 Node.js 中的 net 模块编写自己的静态 http 服务器。 这是我的代码:

var options = {
  hostname: 'localhost',
  port: 8000,
  path: '/read.txt',
  httpVersion : 1.1,
  method: 'GET',
  headers:{
    'Content-Type':'text/plain',
    'connection' : 'keep-alive'
 }
};

function test(){
    var sev = server.start(8000,"./folder",function(e){
        e?(console.log(e)):(console.log("server is connected in port 8888"));
    });
     var req = http.request(options, function(res) {});
     req.on('error', function(e) {
         console.log('problem with request: ' + e.message);
      });
     server.stop(sev,function(e){e?(console.log(e)):(console.log("server is closed"));})
}
test()

这是 server 模块中的 stop 函数:

exports.stop = function(serverID,callback){
    serverID.close();
    callback();
}

但是当我运行它时,它会显示以下消息: 请求问题:连接 ECONNREFUSED。 找不到问题,会不会是node版本的问题?

【问题讨论】:

  • 看起来 'server.stop' 在 'server.start' 有机会完成之前运行(或在 server.start 完成之前运行 http.request)。你的 test 方法正在运行,没有机会让每个都完成。

标签: javascript node.js http module


【解决方案1】:

在关闭服务器之前,您应该关闭套接字。 也尝试在使用 stop 之前延迟程序。

尝试添加:

req.end();
setTimeout(function(){server.stop(sev,function(e){e?(console.log(e)):(console.log("server     is closed"));})
},4000);

【讨论】:

    猜你喜欢
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2014-03-23
    • 2013-03-30
    相关资源
    最近更新 更多