如何从脚本中检索令牌

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 语句,您将在承诺中发送令牌。

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  

}   
};

并且在调用时,您会在 return 中获得带有令牌的承诺,因此

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

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