【发布时间】:2020-07-04 04:42:06
【问题描述】:
我正在尝试发出一个 POST 请求来接收访问令牌,但是该函数没有返回任何内容,并且我得到了未定义。请问这个怎么解决?
function getOAuth() {
fetch("https://accounts.spotify.com/api/token", {
method: "POST",
body:
"grant_type=client_credentials&client_id=" +
clientId +
"&client_secret=" +
clientSecret,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(resp => resp.json()
// Return the response as JSON
)
.then(function(data) {
// Log the API data
console.log("token", data);
// Store token data
let token = {
token: data.access_token,
tokenType:data.token_type,
expires: new Date().getTime() + data.expires_in * 1000
}
return token
})
.catch(function(err) {
// Log any errors
console.log("something went wrong", err);
});
}```
【问题讨论】:
-
你从哪里得到
undefined? -
您的
console.log("token", data)中是否未定义数据?还是整个get0Auth函数返回未定义? -
没有,当我使用 console.log(data) 时,我得到了响应。但是当我调用它时,函数本身返回未定义
-
啊,我明白了。我认为这是一个异步问题。答案贴在下面。
标签: javascript reactjs api post fetch