[英]for loop and forEach loop not working in ejs
我正在開發一個待辦事項應用程序,但我很難讓POST請求正常工作。 我已經嘗試過使用for循環和for Each循環。 不起作用。
<% todos.forEach(item => { %>
<li><%= items.item %></li>
<% });%>
還有這個
<% for(let i=0; i < todos.length; i++) { %>
<li><%= todos[i].item %></li>
<% } %>
我的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);
我的控制器:
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) {});
};
這是錯誤消息:
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>
<% });%>
您的JS代碼基本上是todos.forEach(item => some_formatting(item))
。
在lambda內部,您可以訪問item
,而不是items.item
。
您已經遍歷了“ todos.forEach( item => {});”。 但使用了“ 項目 .item”。
編輯正確的代碼是
<% todos.forEach(function (item) { %>
<li><%= item.item %></li>
<% }) %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.