簡體   English   中英

如何從腳本中檢索令牌

[英]How to retrieve token from script

我有以下腳本:

let url = window.location.href;

const token = {
    authorization(url){
        authentication_code =  url.split("?")[1].split("&")[1].split("=")[1];
        this.postData("https://www.strava.com/oauth/token?grant_type=authorization_code&client_id=3035dd7&client_secret=3db4fddd039117f8029b406fe72669a4472594bfb6b&code=" + authentication_code)
            .then(data =>  data.access_token) // JSON-string from `response.json()` call
            .catch(error => console.error(error));
    },
    postData(url = "") {
        return fetch(url, {
            method: "POST", // *GET, POST, PUT, DELETE, etc.
            cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached   

        })  
            .then(response => response.json()); // parses response to JSON  

    }   
};

該腳本應授權客戶端進行strava並檢索令牌以供進一步使用。 我以某種方式無法理解如何從const令牌中獲取令牌。

當我調用token.authorization()時。 它將授權。 但是我不知道如何從函數中檢索data.access_token。

謝謝。

在this.postData之前可以使用一個簡單的return語句,您將在promise中發送令牌。

let url = window.location.href;

const token = {
authorization(url){
    authentication_code =  url.split("?")[1].split("&")[1].split("=")[1];
    return this.postData("https://www.strava.com/oauth/token?grant_type=authorization_code&client_id=3035dd7&client_secret=3db4fddd039117f8029b406fe72669a4472594bfb6b&code=" + authentication_code)
        .then(data =>  data.access_token) // JSON-string from `response.json()` call
        .catch(error => console.error(error));
},
postData(url = "") {
    return fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached   

    })  
        .then(response => response.json()); // parses response to JSON  

}   
};

當您打電話時,您會得到一個以令牌為回報的承諾,因此

token.authorization(url).then(tokenFromResponse=>console.log(tokenFromResponse));

現在,您可以根據需要使用令牌。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM