I am using the express-paginate module and I am running into some issues around the res.format section in my routes file. I am wondering why this portion is causing the paginate to not be found when I render my view file.
error message:
ReferenceError: /Users/user/Desktop/Projects/node/blog/views/pages/blog.ejs:7
5|
6| <body>
>> 7|
8| <header>
9| <% include ../partials/header %>
10| </header>
paginate is not defined
at buf.push.
</div>
</div>
</div>
<div class="paginate">
.
</div>
<footer>
.buf (eval at <anonymous> (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:242:14), <anonymous>:34:125)
at eval (eval at <anonymous> (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:242:14), <anonymous>:35:23)
at eval (eval at <anonymous> (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:242:14), <anonymous>:37:67)
at /Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:255:15
at Object.exports.render (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:293:13)
at View.exports.renderFile [as engine] (/Users/user/Desktop/Projects/node/blog/node_modules/ejs/lib/ejs.js:323:20)
at View.render (/Users/user/Desktop/Projects/node/blog/node_modules/express/lib/view.js:76:8)
at Function.app.render (/Users/user/Desktop/Projects/node/blog/node_modules/express/lib/application.js:517:10)
at ServerResponse.res.render (/Users/user/Desktop/Projects/node/blog/node_modules/express/lib/response.js:955:7)
at Object.res.format.html (/Users/user/Desktop/Projects/node/blog/app/routes.js:70:13)
routes.js:
var express = require('express');
var app = express();
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
//index
router.route('/')
.get(function(req, res) {
var drinks = [
{ name: 'Bloody Mary', drunkness: 3 },
{ name: 'Martini', drunkness: 5 },
{ name: 'Scotch', drunkness: 10}
];
var tagline = "Lets do this.";
res.render('pages/index', {
drinks: drinks,
tagline: tagline
});
});
app.use(paginate.middleware(10, 50));
//blog
router.route('/blog')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // set the blog content
blogpost.date = req.body.date; // set the date of the post
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog created.' });
});
}) // END POST method
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
Blogpost.find(function(err, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // update the blog content
blogpost.date = req.body.date; // set the date of the post
res.format({
html: function() {
res.render('pages/blog', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}) // END Find Blogpost
}); // END Blogpost.paginate
}); // END GET method
//Route for individual blogs
router.route('/blog/:blogpost_id')
// START GET method blog by ID
.get(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
if (err)
res.send(err);
res.json(blog);
});
}) // END GET method blog by ID
// START PUT method
.put(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // update the blog content
blogpost.date = req.body.date; // set the date of the post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
}) // END PUT method
// START DELETE method
.delete(function(req, res) {
Blogpost.remove({
_id: req.params.blogpost_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
module.exports = router;
paginate.ejs:
<div class="grid">
<div class="col-1-1">
<div class="paginate">
<ul>
<% if (paginate.hasPreiousPages) { %>
<li>
Previous
</li>
<% } %>
<% if (paginate.hasNextPages) { %>
<li>
Next
</li>
<% } %>
</ul>
</div>
</div>
</div>
blog.ejs:
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="grid">
<div class="col-1-1">
<div class="body-content">
<% blogpost.forEach(function(blogpost) { %>
<tr>
<td><h2><%= blogpost.title %></h2></td>
<td><h3><%= blogpost.author %></h3></td>
</tr>
<% }); %>
</div>
</div>
</div>
<div class="paginate">
<% include ../partials/paginate %>
</div>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
On the second line of your routes.js file, you are calling
var app = express();
This line creates a new express app.
Then you use the paginate middleware on this new app,
This is not the 'running' app, you can find the main app instance in your app.js
All your requests are handled by the app created in app.js, this way the paginare middleware never gets called.
To fix this
1: remove these two lines from routes.js
var app = express();
var paginate = require('express-paginate');
2: add in app.js (before you load your routes)
var paginate = require('express-paginate');
app.use(paginate.middleware(10, 50));
Or if you only want to use pagination for that specific set of routes,
remove
var app = express();
and use
router.use(paginate.middleware(10, 50));
Related
I have been working on a code for a to do list, The issue comes when I actually go to a custom list domain and use the delete method, after deleting the method, the website automatically redirects to "localhost:3000/undefined" and the website fails to respond further, all the functionality stops except the display of the existing elements
This is the node js file
const express=require("express");
const bodyParser=require("body-parser");
const ejs = require('ejs');
const mongoose=require("mongoose")
const app=express();
app.use(bodyParser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/todolsDB");
const itemsSchema=new mongoose.Schema({
toDoToday: String
});
const Item=mongoose.model("Item", itemsSchema);
const itemOne=new Item({
toDoToday: "Wake Up"
});
const itemTwo=new Item({
toDoToday: "Get up"
});
const itemThree=new Item({
toDoToday: "Stand up"
});
const Items=[itemOne,itemTwo, itemThree];
const listSchema = {
name: String,
items: [itemsSchema]
};
const List = mongoose.model("List", listSchema);
app.get("/", function(req, res){
Item.find({}, function(err, Items){
if (Items.length===0){
Item.insertMany(Items, function(err){
if(err){
console.log(err)
}
else{
console.log("Succesfully added!")
}
})
res.redirect("/")
}
else{
res.render("lists .ejs", {Day: "Today", newListItem: Items});
}
})});
app.get("/:topic", function(req, res){
const topic=req.params.topic;
List.findOne({name: topic}, function(err, results){
if (!err){
if (!results){
const list = new List({
name: topic,
items: Items
});
list.save();
res.redirect("/" + topic);
}
else{
res.render("lists .ejs", {Day: results.name, newListItem: results.items});
}
}
});
})
app.post("/",function(request, response){
var itemName=request.body.newElement;
const listName=request.body.list
const item=new Item({
toDoToday: itemName
});
if (listName==="Today"){
response.redirect("/");
item.save();
}else{
List.findOne({name:listName}, function(err, results){
console.log(results)
results.items.push(item)
results.save()
response.redirect("/"+listName);
})
}
})
=
app.post("/delete", function(req, res){
const checkedItemId = req.body.checkbox;
const listName = req.body.listName;
if (listName === "Today") {
Item.findByIdAndRemove(checkedItemId, function(err){
if (!err) {
console.log("Successfully deleted checked item.");
res.redirect("/");
}
});
} else {
List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
if (!err){
res.redirect("/" + listName);
}
});
}
});
app.listen(3000, function(){
console.log("connected to port 3000");
})
Here is the "list .ejs" file
<%-include('header.ejs')%>
<body>
<div class="box" id="heading">
<h1>Today is <%= Day %></h1>
</div>
<div class="box">
<% newListItem.forEach(function(item){ %>
<form action="/delete", method="POST">
<div class="item">
<input type="checkbox" name="checkbox" value="<%=item._id%>" onchange="this.form.submit()">
<p><%= item.toDoToday %> </p>
</form>
</div>
<% }) %>
<div>
<form action="/" method="POST" class="item">
<button type="submit" name="list" value=<%= Day %> >+</button>
<input type="text" name="newElement" placeholder="New Element" autocomplete="off">
<input type="hidden" name="listName" id="" value=<%= Day %> > </input>
</div>
</div>
<%-include('footer.ejs')%>
</form>
<script src="" async defer></script>
</body>
</html>
On this route you have req.body.list
app.post("/",function(request, response){
var itemName=request.body.newElement;
const listName=request.body.list
const item=new Item({
toDoToday: itemName
});
And on this route you have req.body.listName
app.post("/delete", function(req, res){
const checkedItemId = req.body.checkbox;
const listName = req.body.listName;
Most likely you are trying to access an object which does not exist, so change the property name.
I'm trying to add a business in Node Express Framework. My issue is that when I fill out the form to add the business, nothing adds to the page. Been trying to figure out this error for some time now.
My business.js code:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Business = require('../models/business');
var passport = require('passport');
// set up the GET handler for the main movies page
router.get('/', function(req, res, next) {
// use the Article model to retrieve all movies
Business.find(function (err, business) {
// if we have an error
if (err) {
console.log(err);
res.end(err);
}
else {
// we got data back
// show the view and pass the data to it
res.render('movies/index', {
title: 'Business',
business: business
});
}
});
});
// GET handler for add to display a blank form
router.get('/add', function(req, res, next) {
// new
if (req.isAuthenticated()) {
res.render('movies/add', {
title: 'Add a New Business'
});
}
else {
res.redirect('/auth/login');
}
});
// POST handler for add to process the form
router.post('/add', function(req, res, next) {
// save a new article using our Article model and mongoose
Business.create( {
name: req.body.name,
city: req.body.city,
province: req.body.province,
postal: req.body.postal,
street: req.body.street
}
);
// redirect to main business page
res.redirect('/business');
});
// GET handler for edit to show the populated form
router.get('/:id', function(req, res, next) {
// create an id variable to store the id from the url
var id = req.params.id;
// look up the selected article
Business.findById(id, function(err, business) {
if (err) {
console.log(err);
res.end(err);
}
else {
// show the edit view
res.render('movies/edit', {
title: 'Business Details',
business: business
});
}
});
});
// POST handler for edit to update the article
router.post('/:id', function(req, res, next) {
// create an id variable to store the id from the url
var id = req.params.id;
// fill the article object
var business = new Business( {
_id: id,
title: req.body.title,
content: req.body.content,
date: req.body.date,
rating: req.body.rating,
actor: req.body.actor
});
// use mongoose and our Article model to update
Business.update( { _id: id }, business, function(err) {
if (err) {
console.log(err)
res.end(err);
}
else {
res.redirect('/business');
}
});
});
//get handler for delete using the article id
router.get('/delete/:id', function(req, res, next){
//grab the id parameter from the url
var id = req.params.id;
Business.remove({ _id: id }, function(err) {
if(err) {
console.log(err);
res.end(err);
}
else {
// show updated business page with redirect
res.redirect('/business');
}
});
});
////auth check
//function isLoggedIn(req, res, next) {
// //is the user authenticated>
// if (req.isAuthenticated()) {
// return next();
// }
// else {
// res.redirect('/auth/login');
// }
//}
// make public
module.exports = router;
My add.ejs code:
<%- include ../partials/header.ejs %>
<main>
<form method="post" action="add">
<fieldset>
<label for="name">Name:*</label>
<input type="text" name="name" required />
</fieldset>
<fieldset>
<label for="city">City:*</label>
<input type="text" name="city" required>
</fieldset>
<fieldset>
<p>
<label>Province:*</label>
<select id="province" required>
<option value="--">--</option>
<option value = "ontario">ON</option>
<option value = "quebec">QC</option>
<option value = "british columbia">BC</option>
<option value = "alberta">AL</option>
<option value="nova scotia">NS</option>
<option value="manitoba">MB</option>
<option value="newfoundland">NL</option>
<option value="pei">PEI</option>
</select>
</p>
</fieldset>
<fieldset>
<label for="postal">Postal Code:*</label>
<input type="text" name="postal" required>
</fieldset>
<fieldset>
<label for="street">Street Name:*</label>
<input type="text" name="street" required>
</fieldset>
<button class="btn btn-primary" type="submit">Save</button>
</form>
</main>
</body>
</html>
Thanks so much in advance!
I am trying to loop my database collections based on a parameter request for one of my schema properties within a view. I have a tags property within my schema that is saved as an array. What I want to be able to do is click on one of the values saved to that array, which will render a page with collections that contain the selected tags value. I have been able to create the route, which will direct me to the individual tag that was clicked, but I receive a tags: [xxx, xxx, xxx] has no method .forEach.that occurs when I call my loop within my view. Why would this be and how should I solve this?
Error message:
TypeError: /Users/user/Desktop/Projects/node/blog/views/pages/tag.ejs:15
13| <div class="col-md-12">
14| <h1><%= blogpost.tags %></h1>
>> 15| <% blogpost.forEach(function(blogpost) { %>
16| <%= blogpost.title %>
17| <% }); %>
18| </div>
Object { _id: 54c7bd20c58f389232000001,
category: 'Analytics/SEO/SEM',
content: '',
tagline: 'yep',
author: 'Author',
blogUrl: 'roger',
featureImage: '/images/event-placeholder.png',
title: 'Roger',
__v: 0,
date: Tue Jan 27 2015 11:29:48 GMT-0500 (EST),
tags: [ 'wolf', ' cow', ' monkey' ] } has no method 'forEach'
Here is my model:
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title: { type: String, unique: true },
featureImage: String,
blogUrl: String,
author: String,
tagline: String,
category: String,
content: String,
tags: { type: Array, lowercase: true },
date: { type: Date, default: Date.now() }
});
BlogPostSchema.post('init', function (post) {
var date = new Date(post.date || Date.now() );
post.dateString = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
});
BlogPostSchema.plugin( mongoosePaginate );
var Blogpost = mongoose.model("Blogpost", BlogPostSchema);
module.exports = mongoose.model('Blogpost', BlogPostSchema);
Here is how I'm calling my individually selected tag within my route (Does my function use the correct parameter call method?):
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
console.log("New instance");
console.log(req.body.tags);
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.featureImage = req.body.featureImage; // set the blog image
blogpost.blogUrl = blogpost.title.toLowerCase().replace(/\s+/g,"-");
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags.trim().split(","); // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(isLoggedIn, function(req, res, blogpost) {
res.render('pages/blogpost-create', {
blogpost : blogpost
});
});
function getTagCriteria(params){
return {
tags: params.blogpost_tags
};
}
router.route('/tag/:blogpost_tags')
.get(function (req, res) {
var tagCriteria = getTagCriteria(req.params);
Blogpost.findOne(tagCriteria, function (err, blogpost) {
if (err)
res.sent(err);
res.render('pages/tag', {
blogpost : blogpost
})
})
});
pages/tag view file:
<div class="container">
<div class="col-md-12">
<h1><%= blogpost.tags %></h1>
<% blogpost.forEach(function(blogpost) { %>
<%= blogpost.title %>
<% }); %>
</div>
</div>
Change your mongo query to:
Blogpost.find(tagCriteria, function (err, blogpost) {
if (err)
res.sent(err);
res.render('pages/tag', {
blogpost : blogpost
})
})
NOTE: blogpost will now be an array [] instead of an object {}
Then in your jade, do the following
<% blogpost.forEach(function(post) { %>
<%= post.title %>
<% }); %>
I am looking to truncate the html on my index page by 100 characters and use a trailing "..." and I'm trying to figure out the best way to do that. Right now, I'm trying to use the package, nodejs-html-truncate, but running into an issue using it. The documentation isn't very clear, at least to me, and I'm calling it within my routes file, but not sure how to truncate within my ejs file. I'm only getting errors. Is there a better package or method to truncate? or is there a clear mistake that I am making when using this package?
routes.js (route('/') is where I am calling the truncate variable)
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
var truncate = require('html-truncate');
//index
router.use(paginate.middleware(10, 50));
router.route('/')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags; // set the tags
blogpost.date = req.body.date; // set the date of the post
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog created.' });
});
}) // END POST method
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
blogpost.title = req.body.title; // get the blog title
blogpost.author = req.body.author; // get the author name
blogpost.tagline = req.body.tagline; // get tagline
blogpost.content = req.body.content; // get the blog content
blogpost.category = req.body.category; // get the category
blogpost.tags = req.body.tags; // get the tags
blogpost.date = req.body.date; // get the date of the post
res.format({
html: function() {
res.render('pages/index', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount,
truncate: truncate
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}); // END Blogpost.paginate
}); // END GET method
//Route for individual blogs
router.route('/blog/:blogpost_id')
// START GET method blog by ID
.get(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {
if (err)
res.send(err);
//res.json(blogpost);
res.render('pages/blogpost', {
blogpost: blogpost
});
});
}) // END GET method blog by ID
// START PUT method
.put(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // update the author name
blogpost.tagline = req.body.tagline; // update the tagline
blogpost.content = req.body.content; // update the blog content
blogpost.category = req.body.category; // update the category
blogpost.tags = req.body.tags; //update the tags
blogpost.date = req.body.date; // update the date of the post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
}) // END PUT method
// START DELETE method
.delete(function(req, res) {
Blogpost.remove({
_id: req.params.blogpost_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
//resume
router.get('/resume', function(req, res) {
res.render('pages/resume');
});
module.exports = router;
index.ejs (I am trying to use this method for blog.content)
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="grid">
<div class="col-9-12">
<div class="blog-content">
<% blogpost.forEach(function(blogpost) { %>
<tr>
<td><h2><%= blogpost.title %></h2></td>
<td><h3><%= blogpost.date %></h3></td>
<td><h3 class="blog-category"><%= blogpost.category %></h3></td>
<td><h3 class="blog-tagline"><i><%= blogpost.tagline %></i></h3></td>
<td><p><%= blogpost.content.truncate(100) %></p></td>
<td>Read More</td>
</tr>
<% }); %>
</div>
</div>
<div class="col-3-12">
<div class="sidebar-personal-information">
<div id="sidebar-social-media">
<ul>
<li><img class="sidebar-social-media-icons" src="images/linkedin.png"></li>
<li><img class="sidebar-social-media-icons" src="images/twitter.png"></li>
</ul>
</div>
<div id="sidebar-current-titles">
<h3>####</h3>
<h4>#####</h4>
</div>
<div id="sidebar-short-summary">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a massa ante. Vestibulum eu enim est. Curabitur a leo venenatis, semper tellus ac, venenatis nisi. Fusce magna urna, cursus quis egestas et, tincidunt ut nisi. Suspendisse potenti. Praesent congue nec lectus vel posuere.</p>
</div>
</div>
<div class="sidebar-newsletter-signup">
<h3>NEWSLETTER</h3>
<form>
<input type="email"></input>
<br>
<input id="email-submit" type="submit" value="Submit" />
</form>
</div>
</div>
</div>
<div class="paginate">
<% include ../partials/paginate %>
</div>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
I am trying to use the mongoose-paginate and express-paginate as advised on both GitHub repositories. I have set up the mongoose-paginate in my model and have the correct response, but can't seem to figure out how to use the express-paginate within my routes and view. I have 11 or 12 entries in my database and it picks up correctly to create a second page, but it isn't finding paginate in my view file.
Right response from model setup:
Pages: 2
[ { content: 'maybe not',
author: 'Connor John',
title: 'This is the 11 test',
_id: 540487ddc787d60000000009,
__v: 0,
date: Thu Sep 04 2014 19:48:02 GMT-0400 (EDT) } ]
blogModel.js (using mongoose-paginate):
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title: String,
author: String,
content: String,
date: { type: Date, default: Date.now }
});
BlogPostSchema.plugin( mongoosePaginate );
var Blogpost = mongoose.model("Blogpost", BlogPostSchema);
Blogpost.paginate({}, 2, 10, function(err, pageCount, blogpost, count) {
if (err) {
console.error(error);
} else {
console.log('Pages:', pageCount);
console.log(blogpost);
}
});
module.exports = mongoose.model('Blogpost', BlogPostSchema);
routes.js (express-paginate):
var express = require('express');
var app = express();
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
//index
router.route('/')
.get(function(req, res) {
var drinks = [
{ name: 'Bloody Mary', drunkness: 3 },
{ name: 'Martini', drunkness: 5 },
{ name: 'Scotch', drunkness: 10}
];
var tagline = "Lets do this.";
res.render('pages/index', {
drinks: drinks,
tagline: tagline
});
});
app.use(paginate.middleware(10, 50));
//blog
router.route('/blog')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // set the blog content
blogpost.date = req.body.date; // set the date of the post
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog created.' });
});
}) // END POST method
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
Blogpost.find(function(err, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // update the blog content
blogpost.date = req.body.date; // set the date of the post
res.format({
html: function() {
res.render('pages/blog', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
});
}) //END Find Blogpost
}); // END GET method
//Route for individual blogs
router.route('/blog/:blogpost_id')
// START GET method blog by ID
.get(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
if (err)
res.send(err);
res.json(blog);
});
}) // END GET method blog by ID
// START PUT method
.put(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // update the blog content
blogpost.date = req.body.date; // set the date of the post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
}) // END PUT method
// START DELETE method
.delete(function(req, res) {
Blogpost.remove({
_id: req.params.blogpost_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
}); //END Paginate
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
module.exports = router;
paginate.ejs (express-paginate):
<div class="grid">
<div class="col-1-1">
<div class="paginate">
<ul>
<% if (paginate.hasPreiousPages) { %>
<li>
Previous
</li>
<% } %>
<% if (paginate.hasNextPages) { %>
<li>
Next
</li>
<% } %>
</ul>
</div>
</div>
</div>
blog.ejs (express-paginate):
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="grid">
<div class="col-1-1">
<div class="body-content">
<% blogpost.forEach(function(blogpost) { %>
<tr>
<td><h2><%= blogpost.title %></h2></td>
<td><h3><%= blogpost.author %></h3></td>
</tr>
<% }); %>
</div>
</div>
</div>
<div class="paginate">
<% include ../partials/paginate %>
</div>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
error message:
ReferenceError: /Users/user/Desktop/Projects/node/blog/views/pages/blog.ejs:7
5|
6| <body>
>> 7|
8| <header>
9| <% include ../partials/header %>
10| </header>