Javascript 使用http.request会生成错误
我一直在使用Node.js中的net模块编写自己的静态http服务器。 这是我的密码:Javascript 使用http.request会生成错误,javascript,node.js,http,module,Javascript,Node.js,Http,Module,我一直在使用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
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()
以下是服务器模块的停止功能:
exports.stop = function(serverID,callback){
serverID.close();
callback();
}
但当我运行它时,它会显示以下消息:
请求问题:连接ECONREFUSSED。
我找不到问题,是否可能是节点版本有问题?在关闭服务器之前,应关闭套接字。 在使用停止之前,请尝试延迟程序 尝试添加:
req.end();
setTimeout(function(){server.stop(sev,function(e){e?(console.log(e)):(console.log("server is closed"));})
},4000);
看起来“server.stop”在“server.start”有机会完成之前运行(或
http.request
在server.start
完成之前)。您的test
方法正在运行一些东西,而没有机会让每一个都完成。