首页 > 解决方案 > nodejs http服务器:出现错误时如何结束请求?

问题描述

在 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,从网络浏览器打开 url,我可以is not a function从日志中获取 msg,但请求过程并未结束(网络浏览器图标保持旋转)。出错后如何立即结束用户请求?

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

标签: node.js

解决方案


将请求侦听器声明为异步函数并将 atry catch与 结合使用await

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

推荐阅读