skip to Main Content

I am currently working on a small account system and I would like to display the user data in an overview webpanel. The user object is passed through directly with the ejs file to the client after auth.
When accessing the user object directly through ejs statements everything works fine. It is also printable in Javascript after this line:

<script> 
const user = JSON.stringify(<%- JSON.stringify(user) %>);            
console.log(user); 
</script>

I can also print this object now in my js file. However I am not able to access certain variables of the object.
I have this function to display certain information on the panel:

function displayUserInfo() {
    console.log("User:" + user);
    console.log("Username:" + user.username);
    document.getElementById('profilePic').src = user.image;
    document.getElementById('usernameInput').value = user.username;
    document.getElementById('emailInput').value = user.email;
    document.getElementById('displaynameInput').value = user.displayname;
}

The output of this code in the console is as follows:

User:{"id":3,"username":"test@test","email":"test@test","image":null,"created_at":"1718643827967.0","salt":undefined,"password":undefined}
Username: undefined

Also all values I try to modify with this function are set to undefined.

I tried to wait for the site to finish loading and afterwards calling the function, but it didn’t help anything. I don’t understand why this is happening as I am able to access the same object on one line and one line later it seemingly disappears.

2

Answers


  1. You’re converting the object to a string with the outer call to JSON.stringify(). Use:

    const user = <%- JSON.stringify(user) %>;  
    

    Note that you can’t concatenate strings and objects, so you should stringify when doing that.

    console.log("User:" + JSON.stringify(user));
    
    Login or Signup to reply.
  2. function displayUserInfo() {
      // Parse the JSON string into an object
      const userObject = JSON.parse(user);
    
      console.log("User:", userObject);
      console.log("Username:", userObject.username);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search