如何从脚本中检索令牌

时间:2018-12-04 16:04:18

标签: javascript ecmascript-6 strava

我有以下脚本:

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。

谢谢。

1 个答案:

答案 0 :(得分:0)

可以在this.postData之前使用简单的return语句,然后您将在令牌中发送令牌。

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));

现在您可以根据需要使用令牌了。