javascript - 如何解析 Rest Api json 响应并将数据插入 Jade 模板(Node.js + express)?

标签 javascript json node.js express pug

因此,我需要在 node.js + express 中解析 json 响应并将数据插入到 jade 文件中。我在 Sinatra 中这样做,这很容易,但在这里.. 响应格式如:

{
  "status": "200",
  "name": "",
  "port": "7777",
  "playercount": "4",
  "players": "name, of, player"
}

最佳答案

express 的res.render()方法允许您传入本地模板变量,并在您的模板中使用它们。例如:

app.route('/', function (req, res) {
  // Your code to get the response, and for example's sake, I'll say it's assigned to 'view_data'.
  if (typeof view_data === 'string') {
    // If you know for sure if your data is going to be an object or a string, 
    // you can leave the if statement out, and instead just parse it (or not if 
    // it's already an object.
    view_data = JSON.parse(view_data);
  }
  res.render('template', view_data);
});

template.jade

h1 This is #{name}
pre= status
p #{playercount} players online

数据可以是任何 JSON 对象,因此如果您以文本形式返回响应,则可以使用 JSON.parse()将其转换为 JSON 对象。

关于javascript - 如何解析 Rest Api json 响应并将数据插入 Jade 模板(Node.js + express)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32876806/

相关文章:

javascript - 引用 JSON 子数据

json - 从同一表中的其他列更新 JSONB 列数据

javascript - React Hooks 中用于传递参数的单击事件的语法是什么

javascript - 使用 Javascript 将文本字段添加到 HTML 表单时出错

c# - 如何从json对象中获取key并转换为数组?

javascript - 将 Firebase 数据库连接到 Express.js 服务器时遇到问题

node.js - 如何在两个docker服务之间实现负载均衡?

json - 访问 Express Web 服务器中的 JSON 值

javascript - 无法使用异步、nodejs 和 mongodb 更改 javascript 对象属性

javascript - Angular2 [innerHTML] if else 验证