When returning a template to render with a message, ejs wont add it to html

I’m unsure how to word the title please edit it as necessary.
The problem I’m having is than in my server code a database query is made to determine if the account name is a dupe, if it is a message is returned with the template:

con.query('SELECT * FROM Users WHERE username = ?', [username], async (err, results) => {
        if (err) {
            return res.render("register.ejs", {
                message: "Error"
            })
        }
        if (results.length > 0) {
            return res.render("register.ejs", {
                message: "Username taken"
           })
        }
})

This message is then meant to be "added" to the html in my ejs file so the user can see it is taken. I can’t seem to get this to work. Ejs file:

 <% if (message) { %>
     <h3><%= message %></h3>
 <% } %>

Also, the code itself does work as the website won’t let me add a duplicate user, the message just won’t show.

3 thoughts on “When returning a template to render with a message, ejs wont add it to html”

  1. Unfortunately, I cannot say for certain what the issue you are experiencing is. When I tried to set up a simple Express app using the same render snippets that you provided, it worked as expected.

    Therefore, my guess is that the issue is not caused by the code snippets that you provided. Without being able to review the rest of your application’s code that is executing, I can only suggest some things for you to review in your investigation:

    • Is the Express app correctly configured to use EJS as the view engine?
    • Does your register.ejs template use client-side JavaScript to alter the UI? If so, can you try temporarily removing the JavaScript to see if it resolves the issue?
    • If you remove everything from the register.ejs template but the EJS code snippet that you provided, does the issue still occur?
    • Is it possible that the code does not enter into either of your if blocks? For example, is it possible that err is evaluating to false and the result.length is equal to 0?

    Below is the app.js file that I used in my testing:

    const express = require('express');
    const app = express();
    
    app.set('view engine', 'ejs');
    
    app.get('/', (req, res) => {
        return res.render("index.ejs", {
            message: "Hello"
       })
    });
    
    app.listen(4000, () => console.log('Example app listening on port 4000!'));
    

    Below is the index.ejs file that I used in my testing:

    <% if (message) { %>
        <h3><%= message %></h3>
    <% } %>
    

    I hope that this helps. Please let us know if you are able to resolve your issue.

    Reply

Leave a Comment