user5854440 user5854440 - 3 months ago 8
Javascript Question

Passport: Login POST request returns user object as String

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.

Answer

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");
    }

});