javascript - Cannot display data in a view in a express nodejs app -
i'm brand new express , node , i'm creating simple express app gets data stored in json file,on post/details view data stored not rendering.i believe way pull data json file can't see error??
here code:
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 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;
i can acess post/details/:id route fine name description , other params don't display. can explain me i'm missing here? - thanks.
correct getbyid function
var getbyid = function (id) { for(var i=0;i<creatordb.length;i++) { if(creatordb[i].id == id){ return creatordb[i]; } } };
Comments
Post a Comment