处理来自POST请求的JSON响应

时间:2015-06-18 14:55:15

标签: json node.js http-post

在向oauth服务器发送POST请求时,我无法读取JSON响应。这是我的POST代码:

var request = require("request");
var querystring = require('querystring');

var postData={
    grant_type: 'code',
    code: code,
    redirect_uri: uri,
    nonce: nonce
};

request.post({
    uri: oauth_token_uri    ,
    headers:
    {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': oauth_code
    },
    body: querystring.stringify(postData)
}, function(err,res, body){
    console.log("BODY:" + res.body);
    console.log("BODY: " + body);
    console.log("Access Token:" + res.body.access_token);
    console.log("Access Token:" + body.access_token);
});

这是控制台中的输出:

BODY:{"access_token":"somecode","refresh_token":"somecode","expires_in":900,"token_type":"bearer","id_token":"someTokenID"}
BODY:{"access_token":"somecode","refresh_token":"somecode","expires_in":900,"token_type":"bearer","id_token":"someTokenID"}
Access Token:undefined
Access Token: undefined

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试以下,

request.post({
    uri: oauth_token_uri    ,
    headers:
    {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': oauth_code
    },
    body: querystring.stringify(postData)
}, function(err,res, body){
    var parsedResponseBody = JSON.parse(body);
    console.log("Access Token:" + parsedResponseBody.access_token);
});

您将以String格式获得回复。您首先需要在JSON对象中解析该响应。