如何从响应正文中检索参数

时间:2019-09-03 09:29:19

标签: node.js express authorization spotify

我正在尝试使用授权代码流(从https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow开始)设置Spotify授权,并且无​​法从Spotify服务器接收令牌。

发出POST请求时,将记录响应正文并设置两个变量:访问令牌和刷新令牌。响应主体确实包含这些标记,但是变量是undefined(请参阅日志)。

console.log("Response.body: ")
console.log(response.body);

var access_token = response.body['access_token'],
    refresh_token = response.body['refresh_token'];
console.log("Access: " + access_token);
console.log("Refresh: " + refresh_token);

我也尝试过body.access_tokenresponse.body.access_token

A 2019-09-03T09:13:03.184411Z Response.body:  
A 2019-09-03T09:13:03.184575Z {"scope":"playlist-modify-private","access_token":"BQAjB5eurOdl3oM2j-8db4pKi-...","token_type":"Bearer","refresh_token":"AQDtEcfw… 
A 2019-09-03T09:13:03.184607Z Access: undefined 
A 2019-09-03T09:13:03.184618Z Refresh: undefined 

1 个答案:

答案 0 :(得分:1)

在尝试访问属性之前,请确保将主体转换为适当的对象。 请尝试以下操作:

const body = JSON.parse(response.body);