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:
How can I use the user object in my external JavaScript ?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.