繁体   English   中英

nodejs http server:如何在收到错误时结束请求?

[英]nodejs http server: how to end a request when got error?

在app.js中:

const server = http.createServer(function (req, res) {
    require('./ctl/index.js')(req,res)
});

在ctl / index.js中:

module.exports =  async (req,res) => {
    func_not_exists(); // for testing purpose
    res.end("ok");
}

在我使用node app.js启动服务器后,从Web浏览器打开url,我可以从日志中获取is not a function msg,但请求进程没有结束(Web浏览器图标保持旋转)。 如何在收到错误后立即结束用户请求?

(我不使用Express.js,而是使用纯http模块。我不想使用process.exit()结束整个过程,只想结束当前的用户请求。)

将请求侦听器声明为异步函数,并将try catchawait结合使用:

const server = http.createServer(async function (req, res) {
  try {
    await require('./ctl/index.js')(req, res)
  } catch (error) {
    res.end('Something went wrong')
  }
})

暂无
暂无

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

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