首页 > 解决方案 > 不明白如何在 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 对象内容。

标签: htmlnode.jsjsonspotify

解决方案


他们使用车把来进行数据绑定。见第 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,我相信你能弄明白。:)


推荐阅读