Yesman77
Yesman77

Reputation: 63

"[object object] string" instead of just JSON

I need to return a JSON object instead of a string using AWS lambda with Node.js.

Any help or suggestions will be appreciated.

This is what is returned:

"[object Object]{\"meta\":{\"request\":\"AP-ITL\",\"status\":\"success\",\"message\":\"OK\",\"code\":200},\"data\":{...}

I also tried JSON.parse() JSON.parse(response) returns: "Unexpected token o in JSON at position 1"

This is my code:

const https = require('https');

exports.handler = (event,context,callback) => {
    let body = {}
    let input = event
    
    let authBody = JSON.stringify({"email": event.username,
          "password": event.password,
      });
      console.log(authBody)
      
console.log(typeof(authBody))
console.log(authBody)
    var details = {
        host: 'host', 
        path: 'endpoint',
        method: 'POST',
        headers: {
        'Content-Type': 'application/json',
    },
    };

    let reqPost =  https.request(details, function(res) {
        console.log("statusCode: ", res.statusCode);
        res.on('data', function (chunk) {
            body += chunk;
        });
        
        res.on('end', function () {
        console.log(body)

           let response = {
                            input: input,
                            body        : body
                            };
           context.succeed(response);
        });
        res.on('error', function () {
          console.log("Result Error", JSON.stringify({body}));
          context.done(null, 'FAILURE');
        });
    });
    reqPost.write(authBody);
    reqPost.end();
};

Upvotes: 1

Views: 486

Answers (2)

Etienne de Martel
Etienne de Martel

Reputation: 36984

Okay, so:

let body = {}

This initialises body with an empty object. Later on, you do:

body += chunk;

chunk is a string, but body isn't at first, so body needs to be turned into a string, which means calling its toString() method, which for an object like that yields [object Object]. That means the response's text will end up always being prefixed with this, and that of course isn't valid JSON.

The fix? Initialise body with an empty string:

let body = ""

Upvotes: 0

ph0enix
ph0enix

Reputation: 774

For the text you have provided, it seems that you are concatenating some JavaScript object to the beginning of your string. In that case, the JSON.parse() returns the error because it is confused by [object Object] inside of something that should be in JSON format (ergo the Unexpected token error).

You should try to figure out what is the first thing that is getting concatenated to your string. If you can't find out why is that happening, the hacky solution would be to eliminate all the elements prior to the {\"meta\": ... tag from the string, but this is not something I would recommend.

Upvotes: 1

Related Questions