Gatonito
Gatonito

Reputation: 2174

NodeJS require's body sometimes is object and sometimes string?

In this function:

exports.subscribeWebhook = function (page, pageToken) {
    return new Promise(function (resolve, reject) {
        request({
            url: 'https://graph.facebook.com/v2.6/me/subscribed_apps',
            qs: {
                access_token: pageToken //Query string: ?access_token=pageToken
            },
            method: 'GET'
        }, function (error, response, body) {

when I try to parse the body with JSON.parse(body) I get no problems, but for this one, which is a POST:

exports.call = function (method, botId, json) {
    return new Promise((resolve, reject) => {
        request({
            url: 'https://api.telegram.org/bot'+mongo.mongoCache.telegramPageTokens[botId]+"/"+method,
            method: 'POST',
            json: json//remember to don't even set the json property if it's undefined (or maybe it's default?)
        }, function (error, response, body) {

when I try to parse the body, I get an error. When I print the body, it's just a JSON object, no other things, but if I do typeof(body) I get Object, but for the first function, I get string.

I know I could just stringfy and then parse but I want to understand what's happening. Why sometimes the body is a string and sometimes it's an object?

Upvotes: 0

Views: 130

Answers (1)

Dmitry Matveev
Dmitry Matveev

Reputation: 5376

setting json property to true sets application/json header for the request and additionally parses response as JSON (so you dont have to)

read about it here

the first request to facebooks returns string encoded response that is why you need to parse it yourself

Upvotes: 1

Related Questions