html - 不明白如何在 node.js 应用程序中处理 JSON 对象键
问题描述
这是一个新手问题。
我已经测试了 web-api-auth-examples: https ://github.com/spotify/web-api-auth-examples
它按预期工作,但我不明白的是 html 代码如何获取正确的数据
<dt>Display name</dt><dd class="clearfix">{{display_name}}</dd>
在这种情况下,数据来自 app.js 中的响应:
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, response, body) {
console.log(body);
});
响应是一个 JSON 对象(https://developer.spotify.com/documentation/web-api/reference/object-model/#user-object-private),它有一个 display_name 的键,它是包含以下内容的字符串:
显示在用户个人资料上的名称。如果不可用,则为 null。
我不明白的是 html 文件如何仅通过使用 html 代码中的键名来获取 JSON 对象内容。
解决方案
他们使用车把来进行数据绑定。见第 62 行index.html
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
换句话说,看到对的引用{{display_name}}
被给定对象键的实际值替换。这是通过script
标签内第 34 行和第 52 行之间定义的车把模板完成的:
<script id="user-profile-template" type="text/x-handlebars-template">
<h1>Logged in as {{display_name}}</h1>
<div class="media">
<div class="pull-left">
<img class="media-object" width="150" src="{{images.0.url}}" />
</div>
<div class="media-body">
<dl class="dl-horizontal">
<dt>Display name</dt><dd class="clearfix">{{display_name}}</dd>
<dt>Id</dt><dd>{{id}}</dd>
<dt>Email</dt><dd>{{email}}</dd>
<dt>Spotify URI</dt><dd><a href="{{external_urls.spotify}}">{{external_urls.spotify}}</a></dd>
<dt>Link</dt><dd><a href="{{href}}">{{href}}</a></dd>
<dt>Profile Image</dt><dd class="clearfix"><a href="{{images.0.url}}">{{images.0.url}}</a></dd>
<dt>Country</dt><dd>{{country}}</dd>
</dl>
</div>
</div>
</script>
阅读Handlebars,我相信你能弄明白。:)
推荐阅读
- machine-learning - jupyter notebook:运行单元不起作用
- javascript - rxfire 订阅未在 componentdidmount 中触发
- json - 条件jq提取层次结构不同位置的两个元素
- go - 在绑定到特定的 127.xxx 地址时侦听多播环回
- html - 我试图让一个按钮转到另一个页面,但它不起作用
- python - 将字节字符串拆分为列
- azure - 是否可以使用站点到站点 (VPN) 连接来连接两个 Azure VNet?
- db2 - 在okd上部署db2
- flutter - 使用反射循环所有可用的图标
- html - 如何使用 bootstrap 4 和 css 创建文件夹形状卡片作为单选按钮?