因此,我需要在 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/