Esta es mi app.all . Básicamente, estoy llamando a una función fetchBuildings basada en el ID/Hash del edificio, luego establezco el title , description y la image según la respuesta:
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) }) }); A veces, el hash es 'undefined' por lo que quiero detener el código cuando eso sucede.
Solo estoy usando return aquí, pero me pregunto si esta es la forma convencional de hacerlo. ¿Hay otra forma más 'adecuada'?
Siempre debe devolver una respuesta o pasar la solicitud a lo largo de la cadena de middleware. Si simplemente regresa, la solicitud se "bloqueará": el cliente seguirá esperando una respuesta que nunca llega y, finalmente, se agotará el tiempo de espera.
Supongamos que pasar un hash de undefined se considera inválido. Podría devolver una respuesta 400 ( "Solicitud incorrecta" ) en ese caso:
if (hash === 'undefined') { return res.sendStatus(400); }Si desea pasar la solicitud, lo que probablemente resultará en una respuesta 404 ( "No encontrado" ) devuelta por Express:
app.all('/:id', function (req, res, next) { const hash = req.params.id const obj = {} if (hash === 'undefined') { return next(); } ... })O transmita explícitamente un error, lo que resulta en una respuesta 500 ( "Error interno del servidor" ) devuelta por Express:
if (hash === 'undefined') { return next(Error('invalid hash')); }