简体   繁体   English

nodejs:TypeError:无法读取未定义的属性(读取“关闭”)

[英]nodejs: TypeError: Cannot read properties of undefined (reading 'close')

process.on('unhandledRejection', (err, promise) => {
    console.log(`Error: ${err.message}`.red);
    //close server & exit process
    let server;
    server.close(() => process.exit(1));
});


C:\Users\Ford\Desktop\DevCamperAPI\server.js:48
    server.close(() => process.exit());
           ^

TypeError: Cannot read properties of undefined (reading 'close')

can someone help me with this?有人可以帮我弄这个吗?

I d like to know why i have this error, can someone help me with this?我想知道为什么我有这个错误,有人可以帮我解决这个问题吗? nodejs节点

Your declaration let server is without assigning any value, server is undefined.您的声明let server没有分配任何值, server 未定义。 So when you call close on undefined object you get this error.因此,当您在未定义的 object 上调用close时,您会收到此错误。

The server variable is undefined in this case thus code execution fails when you try to call a method on an undefined variable.服务器变量在这种情况下是未定义的,因此当您尝试对未定义的变量调用方法时代码执行失败。 There are various ways to create a server using different node modules like https, http, hapi etc. If you have already defined server variable in your module outside this function then you can use that as well to close the server.有多种方法可以使用不同的节点模块创建服务器,例如 https、http、hapi 等。如果您已经在 function 之外的模块中定义了服务器变量,那么您也可以使用它来关闭服务器。 One of the way to do it is:其中一种方法是:

var http = require('http');
var server = http.createServer(function (req, res) {
  res.write('Application starting');
  res.end();
});
server.listen(8080);

process.on('unhandledRejection', (err, promise) => {
    server.close(() => process.exit(1));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM