javascript - 退出 Express 应用程序的正确方法是什么?

标签 javascript express

这是我的app.all。基本上,我根据建筑物 ID/哈希调用 fetchBuildings 函数,然后设置 titledescriptionimage 基于响应:

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/

相关文章:

Javascript fetch Api 不起作用初学者问题

node.js - 如何将 Promise 应用于 app.get?

javascript - 如果启用了自动播放,则无法在加载时暂停 videojs

javascript - 在 CoffeeScript 中调用全局函数

javascript - 在父类上调用方法之前从子元素中删除父类 (javascript/jquery)

javascript - 自动将参数(变量)转换为字符串

node.js - Express 消息 '!=' 在 Pug 中抛出错误

node.js - Sequelize 多对多关系不显示 GET 请求的结果

node.js - 在 express.js 中将请求对象传递给 jade

javascript - 不添加 Nodejs Express cookie