这是我的app.all
。基本上,我根据建筑物 ID/哈希调用 fetchBuildings
函数,然后设置 title
、description
和 image
基于响应:
app.all('/:id', function (req, res) {
const hash = req.params.id
const obj = {}
if (hash === 'undefined') {
obj.title = 'iStaging LiveTour'
obj.description = ''
obj.image = 'https://raw.githubusercontent.com/alexcheninfo/vue-tmux-example/master/app/istaging.jpg'
return
}
fetchBuildingsByHash(hash).then(({title, description, image, isBasicPlan}) => {
if (isBasicPlan) {
obj.title = 'iStaging LiveTour'
obj.description = ''
obj.image = 'https://raw.githubusercontent.com/alexcheninfo/vue-tmux-example/master/app/istaging.jpg'
} else {
obj.title = title || 'iStaging LiveTour'
obj.description = description || ''
obj.image = image || 'https://raw.githubusercontent.com/alexcheninfo/vue-tmux-example/master/app/istaging.jpg'
}
res.render('index.ejs', obj)
}).catch((err) => {
const obj = {
title: 'notFound'
}
res.render('404.ejs', obj)
})
});
有时 hash
是“未定义”
,因此我想在发生这种情况时停止代码。
我只是在这里使用return
,但我想知道这是否是传统的做法。还有其他更“正确”的方法吗?
最佳答案
您应该始终返回响应,或者沿着中间件链传递请求。如果您只是返回,请求将被“卡住”:客户端将继续等待永远不会到来的响应,最终会超时。
假设传递 undefined
的哈希值被视为无效。在这种情况下,您可以返回 400(“错误请求”)响应:
if (hash === 'undefined') {
return res.sendStatus(400);
}
如果您想传递请求,这可能会导致 Express 返回 404(“未找到”)响应:
app.all('/:id', function (req, res, next) {
const hash = req.params.id
const obj = {}
if (hash === 'undefined') {
return next();
}
...
})
或者显式传递错误,导致 Express 返回 500(“内部服务器错误”)响应:
if (hash === 'undefined') {
return next(Error('invalid hash'));
}
关于javascript - 退出 Express 应用程序的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43756482/