Guys I'm going through a udemy class on Node and Express and I've gotten stuck. I'm implementing a route using a GET method ruest. The route has the form of "campgrounds/:id" however, there's a route above that has the name of "/campgrounds/new" which is submission form. here's the link to working web app.
and the webpage of working app
http://webdevcamp-miatech.c9users.io/campgrounds
when you click on any of the buttons "more info" it will redirect to "campgrounds/:id" for now I"m just testing the route and I'm printing some text.
app.js file
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
//connect mongoose db
mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded({extended: true})); //parsing html request
app.set("view engine", "ejs"); //handling vies through ejs pages
//schema/model for data to be inserted in db
var campgroundSchema = new mongoose.Schema({
name: String,
image: String,
description: String
})
var Campground = mongoose.model("Campground", campgroundSchema);
Campground.create({
name: "Salmon Creek",
image: "https://farm6.staticflickr.com/5786/20607281024_5c7b3635cc.jpg",
description: "This is a huge granite hill, no bathroom campground"
}, function(err, campground) {
if(err) {
console.log(err);
}
else {
console.log("Created Campground");
console.log(campground);
}
})
//default route
app.get("/", function(req, res) {
res.render("landing");
})
app.get("/campgrounds", function(req, res) {
Campground.find({}, function(err, allCampgrounds) {
if(err) {
console.log(err);
}
else {
res.render("campgrounds", {campgrounds: allCampgrounds});
}
})
});
//method to add to database and redirect to campgrounds
app.post("/campgrounds", function(req, res) {
// res.send("you hit post route");
//get data from form and add to campgrounds array
var name = req.body.name;
var imgUrl = req.body.image;
var newCampGround = {name: name, image: imgUrl};
//adding to database table
Campground.create(newCampGround, function(err, newlyCreated) {
if(err) {
console.log(err);
}
else {
res.redirect("/campgrounds");
console.log(newlyCreated);
}
});
});
app.get("/campgrounds/new", function(req, res) {
res.render("new.ejs");
})
//displaying especific campground
app.get("campgrounds/:id", function(req, res) {
//find campground with id
// Campground.FindById(req.param)
// res.render("single.ejs");
res.send("This will be the single page!");
})
//starting server
app.listen(process.env.PORT, process.env.IP, function() {
console.log("server started!..");
});
Here's my project on c9.io
https://ide.c9.io/miatech/webdevcamp
missing slash before campgrounds
app.get("/campgrounds/:id", function(req, res) {
//find campground with id
// Campground.FindById(req.param)
// res.render("single.ejs");
res.send("This will be the single page!");
})
Related
After implementing using passport-local not able to open profile page
I'm getting this below error
This page isn’t workinglocalhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
passport-local-strategy.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
passport.use(new LocalStrategy({
usernameField: 'email'
},
function(email, password, done){
User.findOne({email: email}, function(err, user){
if(err){
console.log('Error in finding user --> Passport');
return done(err);
}
if(!user || user.password!=password){
console.log("Invalid username/password");
return done(null, false);
}
return done(null, user);
});
}
));
// serialize user function
passport.serializeUser(function(user, done){
done(null, user.id);
});
//deserialize the user fn
passport.deserializeUser(function(id, done){
User.findById(id, function(err, user){
if(err){
console.log("Error in finding user --> passport");
return done(err);
}
return done(null, user);
});
});
// check if user is authenticated
passport.checkAuthenticated = function(req, res, next){
if(req.isAuthenticated()){
return next();
}
// if the user is not signed in
return res.redirect('/users/sign-in');
}
passport.setAuthenticatedUser = function(req, res, next){
if(req.isAuthenticated()){
// req.user contains current signed in user data from the login page
res.locals.user = req.user;
}
next();
}
module.exports = passport;
users_controller.js
const User = require('../models/user')
module.exports.profile = function(req, res){
if(req.cookies.user_id){
User.findById(req.cookies.user_id, function(err, user){
if(user){
return res.render('profile',{
title:"Profile",
user:user
});
}
else{
return res.redirect('/users/sign-in')
}
})
}
else{
return res.redirect('/users/sign-in');
}
}
// render the sign up and in page
module.exports.signUp = function(req, res){
if(req.isAuthenticated()){
return res.redirect('/users/profile')
}
return res.render('user_sign_up', {
title: "Codeial | Sign Up"
})
}
module.exports.signIn = function(req, res){
if(req.isAuthenticated()){
return res.redirect('/users/profile')
}
return res.render('user_sign_in', {
title: "Codeial | Sign In"
})
}
// get the sign up data
module.exports.create = function(req, res){
if(req.body.password != req.body.confirm_password){
return res.redirect('back')
}
User.findOne({email:req.body.email}, function(err, user){
if(err){console.log('error in finding user in signing up'); return;}
if(!user){
User.create(req.body, function(err, user){
if(err){console.log('error in finding user in signing up'); return;}
return res.redirect('/users/sign-in')
})
}
else{
return res.redirect('back')
}
})
}
module.exports.createSession = function(req, res){
return res.redirect('/');
}
users.js
const express = require('express')
const router = express.Router();
const passport = require('passport');
const usersController = require('../controllers/users_controller');
router.get('/profile',passport.checkAuthenticated,usersController.profile)
router.get('/sign-up', usersController.signUp);
router.get('/sign-in', usersController.signIn);
// in above all codes after get('/sign-up') means when we type the keyword sign-up in the browser we need to render the folllowing page which is userController.signUp
// we are using users_controller.js file by importing
router.post('/create', usersController.create);
router.post('/create-session',passport.authenticate(
'local',
{failureRedirect: '/users/sign-in'},
),usersController.createSession);
// above line post create-session is forms action in user_sign_in.ejs file - when we submit the data of the form the post method is invoked
module.exports = router;
mongoose.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/codeial_development')
const db = mongoose.connection;
db.on('error', console.error.bind(console, "Error connecting to MongoDb"));
db.once('open', function(){
console.log('connected to the database :: MongoDB ')
})
module.exports = db;
index.js
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 8000;
const expressLayouts = require('express-ejs-layouts');
const db = require('./config/mongoose')
const session = require('express-session');
const passport = require('passport');
const passportLocal = require('./config/passport-local-strategy')
const MongoStore = require('connect-mongodb-session')(session)
app.use(express.urlencoded());
/* is a method inbuilt in express to recognize the incoming
Request Object as strings or arrays. This method is called as a
middleware in your application using the code*/
app.use(cookieParser());
app.use(express.static('./assets'));
app.use(expressLayouts);
// extact style and scripts from subpages into the layout
app.set('layout extractStyles', true)
app.set('layout extractScripts', true)
app.set('view engine', 'ejs');
app.set('views','./views')
app.use(session({
name: 'codeial',
secret:'blahsomeone',
saveUninitialized:false,
resave:false,
cookie:{
maxAge: (1000 * 60 * 100)
},
store: new MongoStore({
// mongooseConnection:db
mongoUrl: db._connectionString,
autoRemove: 'disabled'
}, function(err){
console.log(err || 'connect-mongo setup ok')
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.setAuthenticatedUser);
// use express router
app.use('/', require('./routes'));
app.listen(port, function(err){
if(err){console.log(`Error running the server: ${err}`)};
console.log(`Server is running on port: ${port}`);
})
I'm not able to view profile page, its redirecting or getting this error
This page isn’t workinglocalhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
I am trying to do my first API Rest and I am following some tutorials. I am requesting all the articles in a MongoDB database.
This is the code of the main:
var express = require("express"),
app = express(),
http = require("http"),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
server = http.createServer(app),
mongoose = require('mongoose');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
// Import Models and controllers
var models = require('./models/article')(app, mongoose);
var articleCtrl = require('./controllers/articleController');
// Example Route
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
articles.route('/articles/:id')
.get(articleCtrl.findById);
articles.route('/articles')
.get(articleCtrl.findAllarticles)
.post(articleCtrl.addarticle);
app.use('/api', articles);
app.use(router);
mongoose.connect('mongodb://localhost/ustcg', { useNewUrlParser: true ,useUnifiedTopology: true}, function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
});
The code of the controller is here:
// Import article and mongoose
var mongoose = require('mongoose');
var Article = mongoose.model('Article');
//GET - Return a article with specified ID
exports.findById = function(req, res) {
Article.findById(req.params.id, function(err, Article) {
if(err) return res.send(500, err.message);
console.log('GET /article/' + req.params.id);
res.status(200).jsonp(Article);
});
};
//GET - Return all articles in the DB
exports.findAllarticles = function(req, res) {
Article.find(function(err, Article) {
if(err) res.send(500, err.message);
console.log('GET /article')
res.status(200).jsonp(Article);
});
};
//POST - Insert a new article in the DB
exports.addarticle = function(req, res) {
console.log('POST');
console.log(req.body);
var Article = new Article({
title: req.body.title,
paragraphs: req.body.paragraphs
});
Article.save(function(err, Article) {
if(err) return res.send(500, err.message);
res.status(200).jsonp(Article);
});
};
The model:
//We create the model
exports = module.exports = function(app, mongoose) {
var ArticleSchema = new mongoose.Schema({
title: { type: String },
paragraphs: { type: Array },
});
mongoose.model('Article', ArticleSchema);
};
When I tried to request the following http request it send me 404 error. I can not see any logs on the console so it is not entering the methods in order to see the exception is happening so I am stucked with this...
If someone could help me it would be nice.
what is articles variable in your main file.
I tried your code in my machine and struggled with articles variable and you have extra imports which are not required.
Try following code it works fine
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var articleCtrl = require('./sample.controller');
var router = express.Router();
router.get('/', function(req, res) {
res.send("Hello world!");
});
router.get('/articles/:id', articleCtrl.findById);
router.post('/articles', articleCtrl.addarticle);
router.get('/articles', articleCtrl.findAllarticles)
// app.use('/api', router);
app.use(router);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
if you uncomment app.use('/api', router); then you can also use routes as localhost:3000/api/articles
I'm having a small problem here. I want to display 404 not found if I input a wrong route.
The code below only shows 404 not found if I go to http://localhost:3000/
but when I enter http://localhost:3000/wrongroute it displays Cannot GET /wrongroute instead of
404 not found.
const bodyParser = require("body-parser");
const mysql = require('mysql');
const router = express.Router();
const db = mysql.createConnection({
host: 'xxx.xx.xx.xx',
user: 'root',
password: '12345',
database: 'test'
});
db.connect((err) =>{
if(err){
throw err;
}
console.log('Mysql Connected');
// res.send("Mysql Connected");
});
router.post('/login', function (req, res) {
res.send("This is from login route");
res.end();
})
router.post('/signup', function (req, res) {
res.send("This is from signup route");
res.end();
})
router.get('/', function(req, res){
res.send("404 not found");
});
module.exports = router;
Add this route at the END.
router.get("*", (_, res) => res.status(404).send("404 not found"))
Here's your solution. Remember to place the fallback route at the end of your endpoint list.
router.post('/your-route', function (req, res) {
...
});
router.post('/another-route', function (req, res) {
...
});
router.get('*', function(req, res) {
// This is a fallback, in case of no matching
res.status(404);
res.send('Not found.');
});
I am trying to run my app.js locally on my editor, It works in the editor when I try to run it on a browser it loads the first page when I click on a link to enter the site, I get an error UnhandledPromiseRejectionWarning MongoTimeoutError server selection timed out after 30000 ms. I am new at this, this is actually part of a course through udemy. I have searched on google, reddit threads etc. Can't seem to figure this out. Please don't laugh if this is a dumb question. If you need more code let me know I will provide it.
Thanks
here is my app.js
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
flash = require("connect-flash"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
methodOverride = require("method-override"),
Campground = require("./models/campground"),
Comment = require("./models/comment"),
User = require("./models/user")
// seedDB = require("./seeds")
// mongoose.Promise = global.Promise
//requiring routes
var commentRoutes = require("./routes/comments"),
campgroundRoutes = require("./routes/campgrounds"),
indexRoutes = require("./routes/index")
mongoose.connect("mongodb://localhost/yelp_camp_", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
//seedDB(); //seed the database
//PASSPORT CONFIGURATION
app.use(require("express-session")({
secret: "Bodybuilding is fun",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.error = req.flash("error")
res.locals.success = req.flash("success")
next();
});
app.use("/", indexRoutes);
app.use("/campgrounds", campgroundRoutes);
app.use("/campgrounds/:id/comments", commentRoutes);
app.listen(3000, function (){
console.log('The YelpCamp Server Has Started');
});
Campgrounds.js
var express = require("express");
var router = express.Router();
var Campground = require("../models/campground");
var middleware = require("../middleware");
//INDEX - show all campgrounds
router.get("/", function(req, res){
// Get all campgrounds from DB
Campground.find({}, function(err, allCampgrounds){
if(err){
console.log(err);
} else {
res.render("campgrounds/index",{campgrounds:allCampgrounds});
}
});
});
//CREATE - add new campground to DB
router.post("/", middleware.isLoggedIn, function(req, res){
// get data from form and add to campgrounds array
var name = req.body.name;
var price = req.body.price;
var image = req.body.image;
var desc = req.body.description;
var author = {
id: req.user._id,
username: req.user.username
}
var newCampground = {name: name, price: price, image: image, description: desc, author:author}
// Create a new campground and save to DB
Campground.create(newCampground, function(err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to campgrounds page
console.log(newlyCreated);
res.redirect("/campgrounds");
}
});
});
//NEW - show form to create new campground
router.get("/new", middleware.isLoggedIn, function(req, res){
res.render("campgrounds/new");
});
// SHOW - shows more info about one campground
router.get("/:id", function(req, res){
//find the campground with provided ID
Campground.findById(req.params.id).populate("comments").exec(function(err, foundCampground){
if(err || !foundCampground){
req.flash("error", "Campground not found");
res.redirect("back");
} else {
console.log(foundCampground);
//render show template with that campground
res.render("campgrounds/show", {campground: foundCampground});
}
});
});
//EDIT CAMPGROUND ROUTE
router.get("/:id/edit", middleware.checkCampgroundOwnership, function(req, res){
Campground.findById(req.params.id, function(err, foundCampground){
res.render("campgrounds/edit", {campground: foundCampground});
});
});
//UPDATE CAMPGROUND ROUTE
router.put("/:id", middleware.checkCampgroundOwnership, function(req, res){
//find and update the correct campground
Campground.findByIdAndUpdate(req.params.id, req.body.campground, function(err, updatedCampground){
if(err){
res.redirect("/campgrounds");
} else {
res.redirect("/campgrounds/" + req.params.id);
}
});
//redirect somewhere(show page)
});
//DESTROY CAMPGROUND ROUTE
router.delete("/:id", middleware.checkCampgroundOwnership, function(req, res){
Campground.findByIdAndRemove(req.params.id, function(err){
if(err){
res.redirect("/campgrounds");
} else
res.redirect("/campgrounds");
});
});
//middleware
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}
module.exports = router;
Here is my index.js file...
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'QChat' });
});
router.post('/login', function(req, res) {
console.log("processing");
res.send('respond with a resource');
});
module.exports = router;
And here is the code I am using to stored POST data into my mongoDB database. This is located in my app.js file...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user');
var db = mongoose.connection;
var Schema = mongoose.Schema;
db.on('error', console.error);
db.once('open', function() {
console.log("connected");
var Schema = new mongoose.Schema({
mail : String
});
var User = mongoose.model('emp', Schema);
app.post('/login', function(request, response){
console.log("here");
new User({
mail: request.body.email
}).save(function(err, doc) {
if (err)
res.json(err);
else
console.log('save user successfully...');
});
});
Code works fine up until it reaches the app.post, after that it does not seem to read the rest of the code.
I know my index.js file works because when I submit the form, I get to a page that displays respond with a resource (because of the send function). But for some reason, app.post is not being read, am I missing something?
Here is my jade html to show that I am implementing everything correctly...
form(class="inputs", action="/login", method="post")
input(type="text", name="email",class="form-control", id="emailLogin", placeholder="Queen's Email")
input(type="submit",name = "homePage" class ="loginButton" value="Log In" id="loginButton")
Please try to move the following code out of db.once('open')
db.on('error', console.error);
db.once('open', function() {});
app.post('/login', function(request, response){
console.log("here");
new User({
mail: request.body.email
}).save(function(err, doc) {
if (err)
res.json(err);
else
console.log('save user successfully...');
});
});
Another issue in your code, please make sure the first parameter of mongoose.model is User, otherwise, one error could pop up.
var UserSchema = new mongoose.Schema({
mail : String
});
var User = mongoose.model('User', UserSchema);