我是全新的表达和节点,我正在创建一个简单的快递应用程序,将数据存储在json文件中,在我的帖子/详细信息视图中存储的数据不会呈现。我相信是我拉的方式来自json文件的数据,但我看不出错误在哪里?
以下是代码:
posts.json
[
{
"name": "first name",
"description": "test first description",
"slug": "first-name",
"id": "2f065d59"
},
{
"name": "second name",
"description": "test second description",
"slug": "second-name",
"id": "0071b034"
}
]
postslist.js
var express = require('express');
var Creatordb = require('./database/posts.json');
var fs = require('fs');
var uuid = require('node-uuid');
var list = function () {
return Creatordb;
};
var getById = function (id) {
for(var i=0;i<Creatordb.length;i++) {
var id = Creatordb[i].id;
}
return id;
};
exports.list = list;
exports.getById = getById;
post.js
var express = require('express');
var router = express.Router();
var db = require('./postslist');
var fs = require('fs');
exports.index = router.get('/',function (req, res) {
res.render('post/index', { posts: db.list()});
});
exports.form = router.get('/create',function (req, res) {
res.render('post/form');
});
exports.details = router.get('/details/:id',function (req, res, next) {
console.log(req.body.name);
console.log(req.body.description);
console.log(req.body.id);
//console log gives me this:
undefined
undefined
undefined
var post = db.getById(req.params.id);
res.render('post/details', {post:post});
});
module.exports = router;
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var uuid = require('node-uuid');
var routes = require('./routes/index');
var post = require('./routes/post');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', routes);
app.use('/post', post);
module.exports = app;
我可以访问post / details /:id route,但是名称描述和其他参数不会显示。 任何人都可以向我解释我在这里缺少什么吗? - 谢谢。
答案 0 :(得分:0)
更正你的getById函数
var getById = function (id) {
for(var i=0;i<Creatordb.length;i++) {
if(Creatordb[i].id == id){
return Creatordb[i];
}
}
};