【问题标题】:How do I create a json object that gets appended to the actual response in node.js如何创建附加到 node.js 中的实际响应的 json 对象
【发布时间】:2017-01-02 15:59:52
【问题描述】:

我在我的节点应用程序中使用 jSON Web 令牌 (simple-jwt)。我有一个中间件(使用 express.js)来检查令牌是否为有效?()如果为真则返回用户数据。

但是当用户向 localhost:8080/home 或任何其他路由发出 GET 请求时,我需要它返回用户数据(来自 tokenValidation 中间件)以及 localhost:8080/home 的实际内容。我不能使用 response.json({}) 两次,因为这将被视为两个响应。

将用户数据附加到实际 json 响应的标准方法是什么?

如果需要代码,请告诉我。

【问题讨论】:

  • 如果/home 应该返回 HTML,你必须在其中注入用户数据。
  • 没有 html 被返回。我正在为移动应用程序做 api。因此,我只需要返回 json。

标签: javascript json node.js express


【解决方案1】:

在您的中间件中,您可以向reqobject 添加一个新属性。

(req, res, next) => {
  const user = ...queryUser
  req.user = user;
  next();
}

在你的路由处理程序中:

(req, res) => {
  const user = req.user;
  const otherData = { data : 'junk' };
  res.status(200).send({ user, otherData });
}

【讨论】:

  • 是的。这行得通。我认为可能有其他方法可以自动附加 user_data,而无需在每个路由的表达式中显式调用它。
  • 我对node的理解很浅,但我想我刚刚发现了res.write()。即 res.send() 将结束响应, res.write() 将保持打开状态?
  • 您可以创建第二个中间件,您可以在路由处理程序之后应用它并在路由处理程序中调用 next。只有在这个中间件中你才调用 res.send()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-26
相关资源
最近更新 更多