简体   繁体   English

for循环和forEach循环在ejs中不起作用

[英]for loop and forEach loop not working in ejs

I am working on a to-Do App and i'm having a hard time getting the POST request working. 我正在开发一个待办事项应用程序,但我很难让POST请求正常工作。 i have tried using a for loop and a for Each Loop. 我已经尝试过使用for循环和for Each循环。 does not work. 不起作用。

<% todos.forEach(item => { %>
    <li><%= items.item %></li>
<% });%>

and also this 还有这个

<% for(let i=0; i < todos.length; i++) { %>
    <li><%= todos[i].item %></li> 
<% } %>

My app.js: 我的app.js:

const express= require('express');
const todoController = require ('./controllers/todoController');

const app = express();
app.set('view engine', 'ejs');
app.use(express.static('./public'));
todoController(app);

app.listen(3000);

My controller: 我的控制器:

let data = [
    { item: 'wake up and pray' },
    { item: 'go to the gym' }, 
    { item: 'fire my laptop and...CODE!!' }
];

module.exports = function(app) {
    app.get('/todo' ,function(req, res) {
        res.render('todo', {todos:data});
    });

    app.post('/todo',function(req, res) {
        data.push(req.body);
        res.render('todo', {todos:data});
    });

    app.delete('/todo' ,function(req, res) {});
};

This is the error messages: 这是错误消息:

ReferenceError: C:\Users\HP LAPTOP\Desktop\toDoApp\views\todo.ejs:20
   18|         <ul>
   19|                 <% todos.forEach(item => { %>
>> 20|                     <li><%= items.item %></li>
   21|                     <% });%> 
   22|      </ul>
   23| </body>
<% todos.forEach(item => { %>
    <li><%= items.item %></li>
<% });%>

Your JS code is basically todos.forEach(item => some_formatting(item)) . 您的JS代码基本上是todos.forEach(item => some_formatting(item))

Inside the lambda, you have access to item , not to items.item . 在lambda内部,您可以访问item ,而不是items.item

You have looped with "todos.forEach( item => {});" 您已经遍历了“ todos.forEach( item => {});”。 but used " items .item.". 但使用了“ 项目 .item”。

EDITED The Right code is 编辑正确的代码是

<% todos.forEach(function (item) { %>
   <li><%= item.item %></li>
<% }) %>

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

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