node.jsexpressejs

EJS is not working when I use a variable that is passed from server


ESJ Code :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>To-Do-List</title>
    <link rel="stylesheet" href="public\styles.css" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9"
      crossorigin="anonymous"
    />

    <script
      src="https://kit.fontawesome.com/20accab6ba.js"
      crossorigin="anonymous"
    ></script>
  </head>
  <body>
    <div
      class="d-flex flex-column flex-md-row p-4 gap-4 py-md-5 align-items-center justify-content-center"
    >
      <div class="list-group">
        <form
          class="list-group-item d-flex gap-3 bg-body-tertiary"
          action="/submit"
          method="POST"
        >
          <span class="pt-1 form-checked-content">
            <span contenteditable="true" class="w-100" id="taskInput">
              <input
                type="text"
                id="task"
                name="task"
                placeholder="Enter your task"
              />
            </span>
            <small class="d-block text-body-secondary">
              <i
                class="fa-regular fa-clock bi me-1"
                width="1em"
                height="1em"
                style="color: #7a8290"
              ></i>
              <input type="time" id="time" name="time" />
            </small>
          </span>
          <%= variable %>

          <button class="btn btn-primary" type="submit">Submit</button>
        </form>
      </div>
    </div>
  </body>
</html>

I have Tried it Everthing works fine but it does not work when I use something on EJS. I can't Find any solution

Server Code:

import express from "express";
import bodyParser from 'body-parser';
import ejs from "ejs";

import { dirname } from "path";
import { fileURLToPath } from "url";

const app = express();
const port = 3000;
const __dirname = dirname(fileURLToPath(import.meta.url));
const currentTime = new Date();
const hours = currentTime.getHours();
const minutes = currentTime.getMinutes(); 

app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", (req,res) =>{
    res.render(`${__dirname}/views/index.ejs`);
});

app.post('/submit', (req, res) => {
    res.render(`${__dirname}/views/index.ejs`, 
    {
        variable : "Hi",
    })  
  });

app.listen(port, () => {
    console.log("Sever started at port:" + port);
});

Error:

ReferenceError: C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\views\index.ejs:26 24|

25|

26| <%= variable %>

27|

28| Submit

29|

variable is not defined at eval (eval at compile (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:673:12), :12:26) at index (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:703:17) at tryHandleCache (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:274:36) at exports.renderFile [as engine] (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\ejs\lib\ejs.js:491:10) at View.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\view.js:135:8) at tryRender (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\application.js:657:10) at Function.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\application.js:609:3) at ServerResponse.render (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\response.js:1039:7) at file:///C:/Users/Niklaus/Desktop/Web%20Develepment%20Course/BackEnd/4.5%20Capstone%20Prject%20To-Do-List/index.js:19:9 at Layer.handle [as handle_request] (C:\Users\Niklaus\Desktop\Web Develepment Course\BackEnd\4.5 Capstone Prject To-Do-List\node_modules\express\lib\router\layer.js:95:5)


Solution

  • First of all if you're using ejs you should set view engine to serve ejs with:

    app.set("view engine", "ejs");
    

    now you can render your document with your file's name. with :

    app.get("/", (req,res) =>{
        res.render("index");
    });
    

    But it's not related with your problem. Your problem is you are trying to render your index.ejs file without a variable. When you try to access on "/" path your index.ejs file is serving but you didn't declare it so ejs gives error. You should add a if statement on your ejs.

    ....
    <% if (locals.variable) { %> // is variable undefined on local variables ? 
      <%= variable %>
    <% } %>
    <button class="btn btn-primary" type="submit">Submit</button>
    ....
    

    or create a new file to serve "/submit" path