【问题标题】:Do not understand how the JSON object keys is handled in a node.js app不明白如何在 node.js 应用程序中处理 JSON 对象键
【发布时间】:2018-10-15 17:48:39
【问题描述】:

这是一个新手问题。

我已经测试了 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 对象内容。

【问题讨论】:

    标签: html node.js json spotify


    【解决方案1】:

    他们使用车把来进行数据绑定。请参阅index.html 中的第 62 行

    <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
    

    换句话说,看到对{{display_name}} 的引用将被替换为给定对象键的实际值。这是通过在第 34 行和第 52 行之间定义的车把模板完成的,在 script 标记内:

    <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,我相信您能搞清楚。 :)

    【讨论】:

    • 谢谢,正是需要的帮助
    猜你喜欢
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多