【问题标题】:Get Token From Api Dynamically To Access Content动态从 Api 获取令牌以访问内容
【发布时间】:2018-01-09 09:45:30
【问题描述】:

我需要有令牌才能访问我的代码中的公告等内容。但我所做的是复制从 loginUser() 生成的令牌并将其粘贴到获取下的 getAnnouncement() 中。我写了 Authorization : 'Bearer esuigiugeguigiguigi'

function loginUser(){

fetch('http://sample_website.com/api/auth/login', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
        email: document.getElementById("email").value,
        password: document.getElementById("password").value
    })
})
.then(data => data.json() )
.then(data =>  { 

    if(data.response){
        redirect: window.location.replace("../Sample/Home.html") 
    } else{
        alert("Invalid Email or Password");
    }
}) 
.catch((err) => {
    console.error(err);
})

}

function getAnnouncement(){

fetch('http://sample_website.com/api/announcements', {
    method: 'GET',
    headers: {'Content-Type': 'application/json',
    Authorization : 'Bearer esuigiugeguigiguigi'},      
})
.then(data => data.json())
.then(data => { console.log(data)

        const output = document.getElementById("display");
        output.innerHTML = `<ul>
                        <li><h2>${data.data.data[0].title}</h2></li>
                        <li>${data.data.data[0].body}</li>
                        <li>Created: ${data.data.data[0].created_at}</li> 
                        </ul>`;

})
.catch((err) => {
    console.error(err);
})

}

【问题讨论】:

    标签: javascript ecmascript-6 access-token es6-promise fetch-api


    【解决方案1】:

    通常来自 API 调用以获取令牌的响应将保持:

    • 令牌
    • 令牌的持续时间
    • 刷新令牌的链接

    处理此问题的一种基本方法是将令牌数据保存在 localStorage 或内存或其他东西中(您可以自己决定),然后在需要授权的任何请求上使用它。

    如果令牌已过期,相关 API 可能会给出特定错误。然后您可以捕获它,使用链接刷新令牌以获取新令牌,然后重复请求。

    由于手头上没有太多关于 API 的信息,或者您正在做什么以及您正在使用什么(如果有的话)框架,这是我目前可以提供的最佳答案。已经有很多库在处理这些东西,因此您可能还想研究现有的解决方案。

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2016-09-23
      • 2021-01-10
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2012-01-02
      相关资源
      最近更新 更多