如何从脚本中检索令牌



我有以下脚本:

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((时,它会进行授权。但我不知道如何从函数中检索数据.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));

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

最新更新