代码之家  ›  专栏  ›  技术社区  ›  nskalis

前端:如何访问字典并将键的值保存在变量中

  •  -2
  • nskalis  · 技术社区  · 6 年前

    我有一个webapp,它的后端是用Python编写的,并为前端用户呈现一些html。

    我想要实现的是:

    1. 当用户发出 POST 请求 /token ,后端回复一个JSON文档 {"access_token": access_token, "token_type": "bearer"} ; 这已经到位
    2. 在上述情况发生后,对webapp的每个后续请求/导航都应设置 header 命名的 Authorization 相当于 Bearer <access_token> 每个人 GET , 邮递 等,要求它这样做;暂时不重要
    3. 您能否建议并描述如何维护一个名为 access_token 它的默认值是 null ,但当 邮递 到 /代币 ,然后是变量 访问令牌 是初始化的,永远不会通过导航进行更改,除非最终用户进行另一次更改 邮递 请求 /代币 再次重置 访问令牌 新的价值观?

    我不熟悉 jQuery 或 javascript 很你能建议如何初始化、设置、重置变量(例如使用 console.log )基于上述背景信息?

    0 回复  |  直到 6 年前
        1
  •  0
  •   Wesley Smith    6 年前

    您可以将令牌存储在本地存储器或cookies中,这两种方法都可以。然后,当您进行ajax调用时,您将从使用的值中检索该值,并将其添加到传出的ajax请求中。具体如何实现这一点将取决于您使用的具体ajax实现。例如,google“AddAuthTokentojQuery.ajax”,您将找到该库的正确语法

    像这样的方法会奏效:

    // do initial login and get token
    var token = response.access_token;
    
    // store it in local storage
    localStorage.setItem('apiKey', token);
    
    // ... navigate around and what not...
    
    
    // later, when you need to make another call, get the token 
    var token = localStorage.getItem('apiKey');
    
    $.ajax({
        url: url,
        method: "POST",
        dataType: "json",
        //.. other props as needed...
        beforeSend: function (xhr) {
            /* set the Authorization header with the token */
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        },
        success: function (data) {
          // do something cool with data
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // handle errors ...
        }
    });