我使用ejs 1.0并表达4,我有迭代问题。我尝试使用forEach从数据库(mysql)返回我的对象。这是我的快递代码:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
var path = require('path');
var db = require('./config/db.js');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, 'src')));
var router = express.Router();
router.route('/todo')
.post(function(req, res, next){
db.query('INSERT INTO task SET todo_title = ?, todo_description =?',[req.body.title, req.body.description], function(err, info){
if(err) {
console.log('db error', err);
}
console.log('zadanie dodano z id: ');
res.redirect('/api/todo');
});
}).get(function(req, res, next){
db.query('SELECT todo_id, todo_description, data FROM task', function(err, result){
if(err) throw err;
var data = JSON.stringify(result);
res.render('pages/index', {items: data});
});
});
router.route('todo/:todo_id')
.get(function(req, res){
}).post(function(req, res){
}).delete(function(req, res){
});
app.use('/api', router);
app.listen(3000);
和模板:
<!DOCTYPE html>
<html>
<head>
<% include ../partials/header %>
</head>
<body class="container">
<section id="main">
<h1>Welcome!</h1>
<ul>
<% items.forEach(function(item) { %>
<li><% item.todo_id %></li>
<% }); %>
</ul>
<form action="/api/todo" method="POST">
<label for="title">Nazwa zadania</lablel><br>
<input name="title" type="text"><br>
<label for="description">Opis zadania</label><br>
<textarea name="description"></textarea><br>
<button>Wyślij</button>
</form>
</section>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
我也尝试(),但它不起作用。我的对象从get route返回:
[{"todo_id":1,"todo_description":"cos2","data":"2014-10-22T13:02:53.000Z"},{"todo_id":2,"todo_description":"cos2","data":"2014-10-22T13:03:13.000Z"},{"todo_id":3,"todo_description":"cos2","data":"2014-10-22T13:05:00.000Z"},{"todo_id":4,"todo_description":"cos2","data":"2014-10-22T13:06:03.000Z"},{"todo_id":5,"todo_description":"cos2","data":"2014-10-22T13:13:31.000Z"},{"todo_id":6,"todo_description":"asd","data":"2014-10-22T13:15:39.000Z"}]
答案 0 :(得分:2)
问题可能在于使用stringify()
:
db.query('SELECT todo_id, todo_description, data FROM task', function(err, result){
// ...
var data = JSON.stringify(result);
res.render('pages/index', {items: data});
});
字符串值,stringify()
创建,没有.forEach()
方法。并且,res.render()
和EJS不要求值为JSON编码。
您只需将result
Array
Object
分配给items
,而不涉及JSON
:
res.render('pages/index', { items: result });
或者,您需要在视图中parse()
:
<% JSON.parse(items).forEach(function(item) { %>