0

I am passing an object from Express using the render function like so in my index.js file:

app.get("/chat", function(req, res){
  res.render("chat", {user: req.user});
});

I can use it in my chat.ejs file:

<% if(!user){ %>
  <li><a href="/auth/login">Connexion</a></li>
<% } else{ %>
  <li><a href="/profile">Profil</a></li>
  <li><a href="/chat">Chat</a></li>
  <li><a href="/auth/logout">Déconnexion</a></li>
<% } %>

<div id="output"></div>

A chat.js JavaScript file is linked to my chat.ejs file:

<script defer type="text/javascript" src="/script/chat.js"></script>

However my external JavaScript doesn't know the user object when I want to output data inside the div tag:

typingFeedback.innerHTML = "<img src=" + user.thumbnail + "alt='Profile Image />";
let newP = document.createElement("p");
let newTxt = document.createTextNode(data.message);
newP.appendChild(newTxt);
output.appendChild(newP);

Here is a picture of how my files are organize: My Files

How can I use the user object in my external JavaScript ?

1 Answer 1

1

In your chat.ejs you could expose the user as a JavaScript object:

 <script>
  var user = <%- JSON.stringify(user) %>;
</script>

then you can access it as user from your code.

Sign up to request clarification or add additional context in comments.

2 Comments

I added your piece of code in my "chat.ejs" file before the call of my "chat.js" script. Unfortunately, I still have the following error in my "chat.js" script : "Uncaught ReferenceError: user is not defined"
@titi157 did you take over the exact code? does the ejs insertion work as expected? Any other errors?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.