简体   繁体   English

如何在ejs文件nodeJS app中包含JS脚本?

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

I'm doing the nodeJS tuto on openclassroom . 我正在openclassroom上做nodeJS tuto I use the template engine ejs . 我使用模板引擎ejs I try to run a simple JS script but I can't. 我尝试运行一个简单的JS脚本,但我不能。

Here is my app structure: 这是我的app结构:

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

I run my server with app.js : 我用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 : 你可以看到我调用了渲染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. 我的问题是myJS.js脚本没有运行。 There is just an alert('hello') in it and no alert comes on my browser (Firefox) 其中只有alert('hello') ,我的浏览器没有警报(Firefox)

The thing is if I save todo.ejs in todo.html (I erase ejs part), the alert appear. 问题是如果我在todo.html中保存todo.ejs(我擦除了ejs部分),则会出现警报。

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. 我是JS,节点等的初学者,所以解决方案可以是孩子的游戏。

Thank you 谢谢

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')); 我添加了这行app.use(express.static('public')); above the session line. 会话线上方。 And I create a folder '/public' next to app.js 我在app.js旁边创建了一个'/public'文件夹

This way, my server sends file when ejs template require image, CSS, or JS 这样,当ejs模板需要图像,CSS或JS时,我的服务器发送文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM