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

How to parse Rest Api json response and insert data to Jade template (Node.js + express)?

所以,我需要解析 node.js 中的 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 对象。