How to include a JS script in a ejs file, nodeJS app?

Théo.B picture Théo.B · May 2, 2018 · Viewed 7.7k times · Source

I'm doing the nodeJS tuto on openclassroom. I use the template engine ejs. I try to run a simple JS script but I can't.

Here is my app structure:

App_toDoList/
│
├──app.js
├──package-lock.json
├──package.json
│
├── js/
├── node_modules/
└── views/
    ├── modify.ejs
    └── todo.ejs

I run my server with app.js:

var express = require('express');
var session = require('cookie-session'); // Charge le middleware de sessions
var bodyParser = require('body-parser'); // Charge le middleware de gestion des paramètres
var urlencodedParser = bodyParser.urlencoded({ extended: false });

var app = express();


/* On utilise les sessions */
app.use(session({secret: 'todotopsecret'}))


/* S'il n'y a pas de todolist dans la session,
on en crée une vide sous forme d'array avant la suite */
.use(function(req, res, next){
    if (typeof(req.session.todolist) == 'undefined') {
        req.session.todolist = [];
    }
    next();
})

/* On affiche la todolist et le formulaire */
.get('/todo', function(req, res) {
    res.render('todo.ejs', {todolist: req.session.todolist});
})

/* On ajoute un élément à la todolist */
.post('/todo/add/', urlencodedParser, function(req, res) {
    if (req.body.newtodo != '') {
        req.session.todolist.push(req.body.newtodo);
    }
    res.redirect('/todo');
})

/* Supprime un élément de la todolist */
.get('/todo/delete/:id(\\d+)', function(req, res) {
    if (req.params.id != '') {
        req.session.todolist.splice(req.params.id, 1);
    }
    res.redirect('/todo');
})

.get('/todo/modify/:id(\\d+)',function(req,res){
  if (req.params.id != '') {
    res.render('modify.ejs', {index: req.params.id, toModify: req.session.todolist[req.params.id]})
  }
})

.post('/todo/modified/:id(\\d+)', urlencodedParser, function(req, res) {
    if (req.body.modifytodo != '') {
        req.session.todolist[req.params.id]=req.body.modifytodo;
    }
    res.redirect('/todo');
})
/* On redirige vers la todolist si la page demandée n'est pas trouvée */
.use(function(req, res, next){
    res.redirect('/todo');
})

.listen(8080);

You can see that I call the render todo.ejs :

<!DOCTYPE html>

<html>

<head>
  <title>Ma todolist</title>
  <style>
    a {
      text-decoration: none;
      color: black;
    }
  </style>
      <script src="/js/myJS.js"></script>
</head>

<body>
  <h1>Ma todolist</h1>

  <ul>
    <% todolist.forEach(function(todo, index) { %>
      <li>
        <a href="/todo/delete/<%= index %>">✘</a>
        <%= todo %>
          <a href="/todo/modify/<%= index %>">🛠️</a>
      </li>
      <% }); %>
  </ul>

  <form action="/todo/add/" method="post">
    <p>
      <label for="newtodo">Que dois-je faire ?</label>
      <input type="text" name="newtodo" id="newtodo" autofocus />
      <input type="submit" />
    </p>
  </form>

  <input type="text" name="date" id="date">



</body>

</html>

My problem is that myJS.js script doesn't run. There is just an alert('hello') in it and no alert comes on my browser (Firefox)

The thing is if I save todo.ejs in todo.html (I erase ejs part), the alert appear.

I fear the problem comes from how my node server handles directory. I found this but it doesn't help me that much.

If you have any idea or questions feel free to tell me. I am a beginner in JS, node etc so the solution can be a child's play.

Thank you

Answer

Th&#233;o.B picture Théo.B · May 7, 2018

Ok I find my mistake. I have never stated to my node server where are the static files. I add this line app.use(express.static('public')); above the session line. And I create a folder '/public' next to app.js

This way, my server sends file when ejstemplate require image, CSS, or JS