这是我的快速申请代码
app.listen(port, function(){console.log("Connected "+port);})
但是当启动服务器时,它显示错误为"Unhandled 'error' event" at event.js:163
怎么解决?
我应该在每个回调函数上使用error作为参数吗?
答案 0 :(得分:2)
您的服务器需要处理error
事件。请改用
app.listen(port);
app.on('error', onError);
app.on('listening', onListening);
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}