将ejs与express一起使用会返回意外的令牌<已使用

时间:2019-01-11 05:52:10

标签: javascript html node.js ejs

这是我第一次尝试使用Ejs,我认为我的语法都正确。无法理解发生了什么事

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");

const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
let today = new Date();
let options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric"
};

let day = today.toLocaleDateString("en-US", options);
let todoList = ["Sleep","Eat","?"];
app.get("/", function(req, res){
 res.render("index", {
   day: day,
   todoList: todoList
 } );
});
app.post("/", function(req, res){
  let newInput = req.body.todoInput;
  todoList.push(newInput);
});

app.listen(3000, function(){
  console.log("Server started on port 3000.");
});

我的ejs

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Ra's To-do List</title>
</head>

<body>
  <p>
    <%= day %> : Today's to-do list</p>
  <ul>
     <% for (var i=0, i< todoList.length, i++) { %>
    <li> <%= todoList[i] %> </li>
    <% } %>
  </ul>
  <form action="/" method="post">
    <input type="text" name="todoInput" placeholder="Add to your to-do list here">
    <button type="submit" name="button">Add stuff to-do</button>
  </form>
</body>

</html>

我正在使用WSL,并且已正确安装所有模块。编译ejs时,它会在....中给出意外的标记<。香港专业教育学院已经在这里呆了几个小时了,我可能很快就会损坏笔记本电脑:)

  

SyntaxError:意外的令牌<中   /mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/views/index.ejs而   编译ejs

     

如果上述错误无济于事,您可以尝试使用EJS-Lint:   https://github.com/RyanZim/EJS-Lint或者,如果您打算创建一个   异步函数,传递async:true作为选项。       在新功能()       在Template.compile(/mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/node_modules/ejs/lib/ejs.js:618:12)       在Object.compile(/mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/node_modules/ejs/lib/ejs.js:389:16)       在handleCache(/mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/node_modules/ejs/lib/ejs.js:212:18)       在tryHandleCache(/mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/node_modules/ejs/lib/ejs.js:251:16)       在View.exports.renderFile中[作为引擎](/mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/node_modules/ejs/lib/ejs.js:482:10)       在View.render(/mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/node_modules/express/lib/view.js:135:8)       在tryRender(/mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/node_modules/express/lib/application.js:640:10)       在Function.render(/mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/node_modules/express/lib/application.js:592:3)       在ServerResponse.render(/mnt/c/Users/PraveshRana/Desktop/webDev/ejs-todo/node_modules/express/lib/response.js:1008:7)

2 个答案:

答案 0 :(得分:1)

我认为问题在于您在ejs语句中使用逗号而不是分号。

所以代替:

<% for (var i=0, i< todoList.length, i++) { %>

应该是:

<% for (var i=0; i< todoList.length; i++) { %>

干杯, 艾丹。

答案 1 :(得分:0)

使用:

<% for (var i=0; i< todoList.length; i++) { %> 

代替:

<% for (var i=0, i< todoList.length, i++) { %>

,替换为;