node.js - 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()结束整个过程,只想结束当前的用户请求。)
解决方案
将请求侦听器声明为异步函数并将 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')
}
})
推荐阅读
- php - 相同的路由 url 用于 laravel 中的多个中间件
- python - 填补泰坦尼克数据集中缺失的年龄
- python - 读取没有data_only openpyxl python的单元格的值
- r - 有人可以帮我计算所选列中所有行的平均值和标准差吗
- unit-testing - 单元测试包含 vuetify 的 vue 组件
- android - 从 AutoCompleteTextView 中删除顶部和底部的黑色边框
- ansible - Ansible 角色 - 无法检测过滤器插件
- javascript - 设置用户代理不适用于 puppeteer / tor 配置
- angular - 具有大型数据集的 Mat Multi Select 中的性能问题
- python-3.x - 如果boundingRect接触线,如何计算车辆数