ExpressJS Link to Update Content - javascript

I am trying to be able to update my content via my editor, but I'm wondering what part of my application I should be modifying to be able to do this. I have a feeling that it is through the route file, but was wondering if there was a hyperlink method that I should be using from within my view to be able to generate my view with the content I want to edit.
Here is my route file:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
var http = require('http');
var path = require('path');
var aws = require('aws-sdk');
var AWS_ACCESS_KEY = process.env.AWS_ACCESS_KEY;
var AWS_SECRET_KEY = process.env.AWS_SECRET_KEY;
var S3_BUCKET = process.env.S3_BUCKET;
//index
router.use(paginate.middleware(10, 50));
router.route('/')
// 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);
res.format({
html: function() {
res.render('pages/index', {
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)
}, {sortBy: {'date': -1} } ); // END Blogpost.paginate
}); // END GET method
router.get('/sign_s3', function(req, res){
aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var s3_params = {
Bucket: S3_BUCKET,
Key: req.query.s3_object_name,
Expires: 60,
ContentType: req.query.s3_object_type,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function(err, data){
if(err){
console.log(err);
}
else{
var return_data = {
signed_request: data,
url: 'https://'+S3_BUCKET+'.s3.amazonaws.com/'+req.query.s3_object_name
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
console.log("New instance");
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; // 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) {
res.render('pages/blogpost-create');
});
function getSearchCriteria(params) {
return {
blogUrl: params.blogpost_blogUrl
};
}
router.route('/blog/:blogpost_blogUrl')
.get(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOne(searchCriteria, function (err, blogpost) {
if (err)
res.send(err);
res.render('pages/blogpost', {
blogpost: blogpost
})
})
})
.put(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
var updated = getBlogpostUpdate(req.body)
Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
})
.delete(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
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');
});
//portfolio
router.get('/portfolio', function(req, res) {
res.render('pages/portfolio');
});
//login
router.route('/login')
.get(function(req, res) {
res.render('pages/login.ejs', {
message: req.flash('loginMessage')
});
})
.post(passport.authenticate('local-login', {
successRedirect : '/admin',
failureRedirect : '/login',
failurFlash : true
}));
//sign up
/*
router.route('/signup')
.get(function(req, res) {
res.render('pages/signup.ejs', {
message: req.flash('signupMEssage')
});
})
.post(passport.authenticate('local-signup', {
successRedirect : '/admin',
failureRedirect : '/signup',
failurFlash : true
}));
*/
//admin dashboard
router.get('/admin', isLoggedIn, 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);
res.format({
html: function() {
res.render('pages/admin', {
user: req.user,
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)
}, {sortBy: {'date': -1} } ); // END Blogpost.paginate
});
//logout
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
//middleware to make sure user is logged in
// route middleware to make sure
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
module.exports = router;
Blogpost.ejs (Where I'm trying to create a link to edit the post):
<!doctype html>
<html>
<head>
<title>Node Authentication</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Admin</h1>
<h2>Welcome user <%= user.local.email %></h2>
Logout
</div>
<div class="row">
<!-- LOCAL INFORMATION -->
<div class="col-sm-6">
<h3>New Post</h3>
<div class="well">
<h3><span class="fa fa-user"></span> Local</h3>
<p>
<strong>id</strong>: <%= user._id %><br>
<strong>email</strong>: <%= user.local.email %><br>
</p>
</div>
<h3><u>Published Blogposts</u></h3>
<% blogpost.forEach(function(blogpost) { %>
<h4><%= blogpost.title %> Edit</h4>
<% }); %>
</div>
</div>
</div>
</body>
</html>

Related

NodeJS pass Array from MongoDB to EJS file

i'm trying to make an option tag for every item which is in my Array in MongoDB. I have tried some ways but EJS throws me everytime the same error "gate is not defined"..
Here is my function in my route:
router.post('/neueBuchung_spediteur', (req, res) => {
User.findOne({username: req.user}, function (err, user) {
res.render('neueBuchung_spediteur', {
gate: user.gate
});
});
And this is my EJS function:
<select id="torauswahl" name="torauswahl" style="padding:10px;font-size: large; width: 300px">
<% for (var i = 0; i < gate.length; i++){%>
<option value="<%=gate[i]%>"><%=gate[i]%></option>
<%}%>
</select>
thats my full JS file for understanding the logic:
const express = require('express');
const router = express.Router();
// Load Buchung model
const Buchung = require('../DB/models/Buchung');
const User = require('../DB/models/User');
const Tor = require(('../DB/models/Tor'));
const { ensureAuthenticated } = require('../DB/config/auth');
const passport = require('passport');
//Startseite Breuninger
router.get ('/startseite_breuninger', ensureAuthenticated, (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('startseite_breuninger',{
vorname: req.user.vorname,
buchungen: buchungen || []
});
});
});
//startseite Spedi
router.get ('/startseite_spediteur', ensureAuthenticated, (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('startseite_spediteur',{
buchungen: buchungen || []
});
});
});
//Buhchungsübersicht mitarbeiter
router.get('/buchungsuebersicht', (req, res) => res.render('buchungsuebersicht'));
//Buhchungsübersicht spedi
router.get('/neueBuchung_spediteur', (req, res) => res.render('neueBuchung_spediteur'));
//torauswahl spedi
router.get ('/torauswahl', (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('torauswahl',{
buchungen: buchungen || []
});
});
});
//torverwaltung mitarbeiter
router.get ('/torverwaltung', (req, res) =>{
Tor.find(function (err, tor) {
if (err)
return res.send(err);
res.render('torverwaltung',{
tor: tor || [],
});
});
});
//Update Benutzerdaten Breuni
router.post('/update_detailansicht_breuninger',(req,res) =>{
const username = req.body.username;
const telefon = req.body.telefon;
const email = req.body.email;
User.update({username: username}, telefon);
res.render('detailansicht_breuninger');
});
//insert
//insert
router.post('/neueBuchung_spediteur',ensureAuthenticated,(req, res) => {
const {sendungsstruktur, datepicker, timepicker1, timepicker2, sendungen, EUP, EWP, pakete, bemerkung, teile } = req.body;
var user = req.user;
if (errors.length > 0) {
User.findOne({ username: req.user}, function (err, user) {
console.log(JSON.stringify(req.user));
if (err) { throw err; }
if (user) {
res.render('neueBuchung_spediteur', {
gate: user.gate || []
});
}
});
}
const newBuchung = new Buchung({
sendungsstruktur,
datepicker,
timepicker1,
timepicker2,
sendungen,
EUP,
EWP,
pakete,
bemerkung,
teile
});
newBuchung.save()
.then(buchung =>{
res.send('saved')
})
.catch(err=>console.log(err));
console.log(newBuchung)
});
router.post(
'/login',
passport.authenticate('local', {
failureRedirect: '/login'
}), (req, res) => {
if (req.user.admin == "spediteur") {
res.redirect('/buchungen/startseite_spediteur');
} else {
res.redirect('/buchungen/startseite_breuninger');
}
});
module.exports = router;
Im thankful for any help :)
I think the issue is that req.user is undefined. Can you try logging req.user during your route function?
router.post('/neueBuchung_spediteur', (req, res) => {
User.findOne({username: req.user}, function (err, user) {
console.log(JSON.stringify(req.user))
res.render('neueBuchung_spediteur', {
gate: user.gate
});
});

Integrate angularjs with node api?

I have my node routes as below
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
//var morgan = require('morgan'); // log requests to the console (express4)
//var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override');
var fs = require('fs');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var User = require('./models/users');
var Dummy = require('./models/dummycar');
//app.use(express.static(__dirname + '/')); // set the static files location /public/img will be /img for users
//app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
// get users list
app.get('/api/users',function(req, res) {
User.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
});
//create users
app.post('/api/users', function(req, res) {
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.save(function(err) {
if (err)
res.send(err);
User.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
});
});
//create cars
app.post('/api/cars', function(req, res) {
var dummy = new Dummy();
dummy.name = req.body.name;
dummy.brand = req.body.brand;
dummy.class = req.body.class;
dummy.price = req.body.price;
dummy.available = req.body.available;
dummy.save(function(err) {
if (err)
res.send(err);
res.send("sucess");
});
});
//list cars
app.get('/api/cars',function(req, res) {
Dummy.find(function(err, dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
//list cars by available
app.get('/api/cars/available',function(req, res) {
Dummy.find({available:'true'},function(err, dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
// list cars by class
app.get('/api/cars/:classtype',function(req, res) {
Dummy.find({class:req.params.classtype}, function(err,dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
// list cars by price
app.get('/api/cars/price/:startvalue/:endvalue',function(req, res) {
Dummy.find({price:{$gte:req.params.startvalue,$lte:req.params.endvalue}}, function(err,dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
// booking option by sending date and name
app.get('/api/cars/book/:nametype',function(req, res) {
Dummy.findOne({name:req.params.nametype}, function(err, dummy) {
if (err)
res.send(err);
dummy.available = false;
dummy.save(function(err) {
if (err)
res.send(err);
res.send("updated");
});
});
});
// user authentication
app.get('/api/users/:usernametype/:passwordtype',function(req, res) {
User.findOne({$and:[{username:req.params.usernametype},{password:req.params.passwordtype}]}, function(err, user) {
if (err)
res.send(err);
else {
if (user == null)
res.send(false);
else
res.send(true);
}
});
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
//app.use('/api', router);
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./view/intro.html'); // load the single view file (angular will handle the page changes on the front-end)
});
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('server running on ' + port);
My model are
//dummycar.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var dummySchema = new Schema({
name: {
type: String,
required: true
},
brand: {
type: String
},
class: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
available: {
type: Boolean,
required: true
},
dateavailable: {
type: Date,
default:Date.now }
});
module.exports = mongoose.model('Dummy', dummySchema);
//user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', userSchema);
But i don't how to call them from angular.js
I have my intro.html as below
<!-- public/index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
<title>Starter Node and Angular</title>
<!-- CSS -->
<link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css"> <!-- custom styles -->
<!-- JS -->
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<!-- ANGULAR CUSTOM -->
<script src="js/controllers/MainCtrl.js"></script>
<script src="js/controllers/NerdCtrl.js"></script>
<script src="js/services/NerdService.js"></script>
<script src="js/appRoutes.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="sampleApp" ng-controller="NerdController">
<div class="container">
<!-- HEADER -->
<nav class="navbar navbar-inverse">
<div class="navbar-header">
<a class="navbar-brand" href="/">Stencil: Node and Angular</a>
</div>
<!-- LINK TO OUR PAGES. ANGULAR HANDLES THE ROUTING HERE -->
<ul class="nav navbar-nav">
<li>Nerds</li>
</ul>
</nav>
<!-- ANGULAR DYNAMIC CONTENT -->
<div ng-view></div>
</div>
</body>
</html>
I would like to call them when user click each link. If some one could help me developing angularjs services.
Best would be to create a service but you can do it in the ctrl aswell
// users.service.js
var userService = angular.module('app.userService', ['ngResource'])
.factory('users', function ($http, $q) {
var that = this;
this.data = {};
var url = '';
var factory = {
get: get
};
function get() {
url = '/api/users';
var defer = $q.defer();
$http.get(url).
success(function (data, status, headers, config) {
defer.resolve(data);
}).
error(function (data, status, headers, config) {
defer.reject(data);
});
return defer.promise;
};
});
// some.controller.js
angular.module('app.somectrl', ['app.userService'])
.controller(someController);
function someController(userService) {
userService.get().then(function (res) {
// do sth
}, function (err) {
// handle error
});
}

express js cannot GET /page

I am very stuck with a routing error on express.js. I am using jade to render my page views. I have read all the docs and refactored many times to no avail.
This is the plain contents of the link that is pointing to the '/sell' route.
index.jade
include layout
html
button.btn.btn-primary(type='submit', href='/sell') Add Item
When clicking this button the browser returns the following as a 404:
Cannot GET /sell
The problem here is that all other routes work correctly, if you are to modify the above href to other pages i.e. '/' , '/sign_in', etc no error occurs. The problem appears to be isolated to the '/sell' route.
The controller with the '/sell' route is below:
server.js
var dotenv = require('dotenv');
dotenv.load();
var session = require('express-session')
var nodemailer = require('nodemailer');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bcrypt = require('bcrypt');
var async = require('async');
var crypto = require('crypto');
var cookieParser = require('cookie-parser');
var flash = require('express-flash');
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var root = __dirname;
var path = require('path');
var User = require('./models/user');
var bodyParser = require('body-parser');
var errorHelper = require('mongoose-error-helper').errorHelper;
var validator = require('validator');
var Item = require("./models/item")
var username, email, password, owner, product_name, condition, details, price;
mongoose.connect(process.env.MONGODB_CONGO_DEV);
// Middleware
app.set('views', 'app/views');
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(cookieParser());
app.use(session( {
secret: 'session secret key',
resave: false,
saveUninitialized: true
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
// Routing
app.get('/', function(req,res) {
res.render('index', {
title: 'Congo',
message: 'Congo',
user: req.user
});
});
app.get('/sell', function(req,res) {
res.render('item', {
title: 'Congo - Sell',
message: 'Sell',
user: req.user
});
});
app.get('/sign_in', function(req,res) {
res.render('sign_in', {
title: 'Congo',
message: 'sign in motherfucker',
user: req.user
});
});
app.post('/sign_in', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) return next(err)
if (!user) {
req.flash('error', 'Incorrect login details');
return res.redirect('/sign_in')
};
req.logIn(user, function(err) {
if (err) return next(err);
res.
return res.redirect('/');
});
})(req, res, next);
});
app.get('/sign_up', function(req, res) {
res.render('sign_up', {
title: 'Congo',
message: 'sign up',
user: req.user
});
});
app.post('/sign_up', function(req, res) {
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password
});
if (req.body.confirm != req.body.password) {
req.flash('error', 'Password do not match')
res.redirect('/sign_up')
};
else if (validator.isEmail(req.body.email) === false) {
req.flash('error', 'Invalid email address')
res.redirect('/sign_up')
};
else {
user.save(function(err) {
if (err) {
req.flash('error', 'Email already in use')
res.redirect('/sign_up')
} else {
req.logIn(user, function(err) {
res.redirect('/');
});
}
});
};
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.get('/forgot', function(req, res) {
res.render('forgot', {
user: req.user,
message: 'you wally'
});
});
app.get('/profile', function(req, res) {
res.render('profile', {
user: req.user,
message: 'User profile'
});
});
app.post('/forgot', function(req, res, next) {
async.waterfall([
function(done) {
crypto.randomBytes(20, function(err, buf) {
var token = buf.toString('hex');
done(err, token);
});
},
function(token, done) {
User.findOne({ email: req.body.email }, function(err, user) {
if (!user) {
req.flash('error', 'No account with that email address exists.');
return res.redirect('/forgot');
};
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
user.save(function(err) {
done(err, token, user);
});
});
},
function(token, user, done) {
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: 'harryandrew.dix#gmail.com',
pass: process.env.GMAIL_PASS
};
});
var mailOptions = {
to: user.email,
from: 'passwordreset#demo.com',
subject: 'Node.js Password Reset',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('info', 'An e-mail has been sent to ' + user.email + ' with further instructions.');
done(err, 'done');
});
};
], function(err) {
if (err) return next(err);
res.redirect('/forgot');
});
});
app.get('/reset/:token', function(req,res) {
User.findOne({resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now()}}, function(err,user) {
if (!user) {
req.flash('error', 'Password reset token invalid or expired.');
return res.redirect('/forgot');
}
res.render('reset', {
user: req.user,
message: 'reset dem pass'
});
});
});
app.post('/reset/:token', function(req, res) {
async.waterfall([
function(done) {
User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('error', 'Password reset token is invalid or has expired.');
return res.redirect('back');
};
user.password = req.body.password;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
user.save(function(err) {
req.logIn(user, function(err) {
done(err, user);
});
});
});
},
function(user, done) {
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: 'harryandrew.dix#gmail.com',
pass: process.env.GMAIL_PASS
};
});
var mailOptions = {
to: user.email,
from: 'passwordreset#demo.com',
subject: 'Your password has been changed',
text: 'Hello,\n\n' +
'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
};
smtpTransport.sendMail(mailOptions, function(err) {
req.flash('success', 'Success! Your password has been changed.');
done(err);
});
};
], function(err) {
res.redirect('/');
});
});
// app.post('/add_item', function(req, res) {
// var item = new Item({
// owner: req.user.id,
// product_name: req.body.product_name,
// condition: req.body.condition,
// details: req.body.details,
// price: req.body.price
// });
// item.save(function(err) {
// if (err) {
// req.flash('error', 'Something went wrong, make sure you are signed in.')
// res.redirect('/add_item');
// } else {
// req.logIn(item, function(err) {
// res.redirect('/user_profile');
// });
// };
// });
// });
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
});
item.jade
include layout
html
block content
form(method='POST')
legend(style='font-family: Raleway; font-size: 30px;') Item Details
.form-group
label(for='product_name') Product Name
input.form-control(type='text', name='product_name', placeholder='include product name, brand, condition, colour etc.', required autofocus)
.form-group
label(for='condition') Condition
input.form-control(type='text', name='condition', placeholder='e.g. New, Used', required)
.form-group
label(for='image') Image
input.form-control(type='file', name='image')
.form-group
label(for='details') Details
textarea.form-control(name='details', cols='40', rows='5')
.form-group
label(for='price') Price
.input-group
.input-group-addon £
input.form-control(type='text', placeholder='Amount', required)
.input-group-addon .00
br
br
button#btnSubmit.btn.btn-primary(type='submit') Post Item
I think it's acting as form post and tries to reach app.post('/sell')
Change it:
button.btn.btn-primary(type='submit', href='/sell') Add Item
to:
a.btn.btn-primary(href='/sell') Add Item
also remove some parts of middleware and keep only these lines:
app.set('views', 'app/views');
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
and then navigate in Your browser to /sell route, check if it's working.
if Yes - so problem with one of middlewares that we have deleted to check.
You should add a logger middleware and see what error the server gives when you try to go to that route. Another thing to try would be to rename the sell route and see if that works. That could indicate a conflict with another one of your routes, although it's not clear where this would be from looking at your code.

ExpressJs - Finding records matching route parameter

I have been building out a tagging system for my ExpressJS application and I have been able to create my routing to pick up on the individual tags that are used for my record, but the issue I am running into is trying to display content associated with the selected tag. For instance a record has a tag "Mouse", when clicked the route correctly goes to /tag/mouse, but I'm not sure if I should use a loop within my template to display only those values or if I should really be using a method within my route. I'm currently using nothing and the value being displayed on the tag page is undefined. I have a feeling the route method is what I am looking for.
Here is the main focus of my routes file:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
var http = require('http');
var path = require('path');
var aws = require('aws-sdk');
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 getSearchCriteria(params) {
return {
blogUrl: params.blogpost_blogUrl
};
}
router.route('/blog/:blogpost_blogUrl')
.get(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOne(searchCriteria, function (err, blogpost) {
if (err)
res.send(err);
res.render('pages/blogpost', {
blogpost: blogpost
})
})
})
.put(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
var updated = getBlogpostUpdate(req.body)
Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
})
.delete(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
router.get('/tag/:blogpost_tags', 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);
res.format({
html: function() {
res.render('pages/tag', {
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)
}, {sortBy: {'date': -1} } ); // END Blogpost.paginate
});
Model:
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title: String,
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);
Tag page (EJS):
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="container">
<div class="col-md-12">
<%= blogpost.tags %>
</div>
</div>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>

ExpressJS PUT method undefined objecty issue

I am trying to use the PUT method to update a record in my database, but I am running into a issue where the object is not defined.
ReferenceError: blogpost is not defined
I am referencing this tutorial with my routing steps and noticed that despite the variable being defined in my /blogs route, meaning that it is local to that function, that in the tutorial, they don't define the variable again when routing their put method. They simply call the object's property that they plan to update. Is there a reason why I'm not able to access this object? Is it a scope issue?
routes.js:
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
//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
});
});
//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.content = req.body.content; // set the blog content
//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) {
Blogpost.find(function(err, blogs) {
if (err)
res.send(err);
res.json(blogs);
});
}); // 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, blog) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.content = req.body.content; // update the blog content
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
module.exports = router;
Specific area where the issue is created:
// START PUT method
.put(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.content = req.body.content; // update the blog content
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
});
Blogpost.findById(req.params.blogpost_id, function(err, blog) {
Should be:
Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {

Categories