0

I'm trying to login to an existing user via Passport. The login goes through successfully, but the user object returns as a string. This presents a problem because I run a for in loop on the object; instead of running on each object key, it runs it on each character. Here is my code:

Post Request

PostRequest( '/auth/login', login, 'application/json', ( status, user ) => {

    if ( status == 200 ) {
        //If user is passed, then set cookie for user. Otherwise display error.
        for ( const key in user ) {
            console.log( key + " : " + user[key] );
        }

        window.open( "/user/" + user.username, "_parent" );
    } else {
        console.log("error");
    }

});

Ajax Call

function PostRequest( url, data, MIMEType, callback = undefined ) {

    data = JSON.stringify(data);
    xhr.open( 'POST', url );
    xhr.setRequestHeader( 'Content-Type', MIMEType );
    xhr.send( data );

    xhr.onload = () => {
        return callback( xhr.status, xhr.responseText );    
    }

}

How do I get the return data to be a JSON object rather than a string? All help is appreciated.

user5854440
  • 271
  • 4
  • 14

1 Answers1

1

It looks like user is a stringified object (JSON). If so, you need to parse it using JSON.parse first.

PostRequest( '/auth/login', login, 'application/json', ( status, user ) => {

    if ( status == 200 ) {
        //If user is passed, then set cookie for user. Otherwise display error.
        var userJson = JSON.parse(user);

        for ( const key in userJson ) {
            console.log( key + " : " + userJson[key] );
        }

        window.open( "/user/" + userJson.username, "_parent" );
    } else {
        console.log("error");
    }

});
Community
  • 1
  • 1
Minderov
  • 521
  • 1
  • 5
  • 20
  • I kept trying to do this in the `PostRequest` function and it never worked. Location Location Location. Thank you so much! – user5854440 Aug 27 '16 at 03:41