I want to pass JS variables to an EJS file, how can I do this?

Asked

Viewed 24 times

0

I’ve been trying to chat, and the client’s username is on req.session client. And to show the user’s number in the corner of the screen, I need to take this user’s variable, for this, in index.js I put this:

app.get("/", (req, res) => {
    if(req.session.userName == ''){
        res.render('redirectLogin.ejs')
    }
    if(!req.session.userName){
        req.session.userName == ''
        res.render('redirectLogin.ejs')
    }else{
        res.render('index.ejs', { userName: req.session.userName });
    }
});

and in that index.ejs:

<script type="text/javascript">

        var name = <%=userName%>

        var socket = io();

        var messages = document.getElementById('messages');
        var usersUl = document.getElementById('users');
        var usersTitle = document.getElementById('usersH1');
        var form = document.getElementById('form');

And you’re making a mistake in that part: var name = <%=userName%>, saying I can’t put the <%= %>

  • 1

    Try using quotation marks: var name = "<%=userName%>"

  • I thought it would be harder, vlw worked

  • now I want to do the opposite, I want to pass a variable from index.ejs, to the server, how do I do this???????????

  • 1

    There is no way to do this directly . You will have to use JS and make an HTTP call (via Xios or fetch) for the server to receive this value.

  • is that I put points system by message, so I wanted the points to be saved in the req.session

  • ah, I’ve managed to do that with socket.io

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.