首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从脚本中检索令牌

如何从脚本中检索令牌
EN

Stack Overflow用户
提问于 2018-12-05 00:04:18
回答 1查看 318关注 0票数 0

我有以下脚本:

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。

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-05 04:09:13

可以在this.postData之前使用一个简单的返回语句,然后在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));

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53616944

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档