I am working on a Nodejs Web application project which is based on Express Framework. I am working on creating a Sign up page. After giving the username and password the url should be redirected to profile page. In the views folder I created a file "profile.hbs". But the profile is not being recognized and I getting 404 not found. Please share your ideas on how to debug this issue.Thanks in advance.
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressHbs=require('express-handlebars');
var mongoose=require('mongoose');
var session=require('express-session');
var passport=require('passport');
var flash=require('connect-flash');
const mocha=require('mocha');
var validator=require('express-validator');
var indexRouter = require('./routes/index');
//var usersRouter = require('./routes/users');
var app = express();
mongoose.connect('mongodb://localhost:27017/shopping');
require('./config/passport');
// view engine setup
app.engine('.hbs',expressHbs({defaultLayout:'layout',extname:'.hbs'}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({secret:'mysupersecret',resave:false,saveUninitialized:false}));
app.use(passport.initialize());
app.use(flash());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
//app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Routing file
var express = require('express');
var router = express.Router();
var csrf=require('csurf');
var passport=require('passport');
const canine= require('../models/dogfood');
var csrfProtection=csrf();
router.use(csrfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
canine.find(function(err,docs){
var productChunks=[];
var chunkSize=3;
for(var i=0;i<docs.length;i += chunkSize){
productChunks.push(docs.slice(i,i+chunkSize));
}
res.render('shop/index', { title: 'Express',diets:productChunks});
});
});
router.get('/user/signup',function(req,res,next){
res.render('user/signup',{csrfToken:req.csrfToken()})
});
router.post('user/signup',passport.authenticate('local.signup',{
successRedirect:'user/profile',
failureRedirect:'user/signup',
failureFlash:true
}));
router.get('user/profile',function(req,res,next) {
res.render('user/profile');
});
module.exports = router;
Apart from adding a view file you should also add a new route which renders that view
app.get('/', function (req, res) {
res.render('profile.hbs', {
title: 'Profile',
// and any extra data you need, probably coming from your auth middleware
});
});
Related
I am doing the Coursera course on Server-Side Development and I have followed the instructions precisely. I keep getting this error, however. There are no relevant posts on their Discussion platform, and I cannot seem to debug because (if you see below) the trace is solely referring to files in the node_modules folder that are established upon initialization of the project as a node project. Thus, I am stuck. Presumably there is "something" wrong with my code, but since the trace is not referring to anything I coded, I am lost. I also thought that perhaps I failed to install express, but I have tried reinstalling as per instructions in the course and that doesn't seem to solve the problem.
Has anyone encountered this specific error when creating a Node.js project and, if so, what did you do to solve?
Login sessions require session support. Did you forget to use express-session middleware?
This is the app.js code:
var createError = require('http-errors');
const express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const session = require('express-session');
var FileStore = require('session-file-store')(session);
var passport = require('passport');
var authenticate = require('./authenticate');
var config = require('./config');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var dishRouter = require('./routes/dishRouter');
var leaderRouter = require('./routes/leaderRouter');
var promoRouter = require('./routes/promoRouter');
const uploadRouter = require('./routes/uploadRouter');
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const Dishes = require('./models/dishes');
const url = config.mongoUrl;
const connect = mongoose.connect(url);
connect.then((db) => {
console.log('Connected correctly to the server.');
}, (err) => {console.log(err); });
var app = express();
// Secure traffic only
app.all('*', (req, res, next) => {
if (req.secure) {
return next();
}
else {
res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url);
}
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session()); // FOund this in the Forum not Given Code
// Note that these two mountings occur before authentication
app.use('/', indexRouter);
app.use('/users', usersRouter);
// Authentication is now completed
app.use(express.static(path.join(__dirname, 'public')));
// This is where the mounting occurs
app.use('/dishes', dishRouter);
app.use('/promotions', promoRouter);
app.use('/leaders', leaderRouter);
app.use('/imageUpload',uploadRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
This is the index.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Per the doc for session-file-store, the proper initialization is this:
const session = require('express-session');
const FileStore = require('session-file-store')(session);
const fileStoreOptions = {};
app.use(session({
store: new FileStore(fileStoreOptions),
secret: 'keyboard cat'
}));
You seem to be missing the app.use() part that actually initializes express-session.
I am new to NodeJs and Express. I want to make an Ajax call from an ejs file :
<script>
$(document).ready(function() {
$.ajax({
async : false,
url: "/organisation/list",
success : function(data, status, xhr) {
alert("finsihed");
}
});
});
</script>
Here is the config of my app :
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Here is the index.js file :
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
How to make it possible to reach the Ajax url /organisation/list ? Should I create another file in the routes directory ?
You can simply write a route like this :
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET organisation list. */
router.get('/organisation/list', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
or you can create a separate file that handles all requests related to the organization.
app.js
app.use('/organization', require('./routes/organization.js');
routes/organization.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/list', function(req, res, next) {
//res.render('index', { title: 'Express' });
res.status(200).json([]);
});
module.exports = router;
I generated a project with express-generator.
In my routes directory, i have 2 files : index.js and users.js, and about.js that handles the /about route.
Accessing /about results in Error 404 : Page Not found.
When adding the handler for /about in app.js, the error was gone.
./app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index')
var aboutRouter = require('./routes/about');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/about', aboutRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development\
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
./route/index.js:
var express = require('express');
var app = express();
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.json( {
message : "Home Page (Requeste for list)",
method : req.method,
Succes : "True"
});
// res.render('index', { title: 'Express' });
})
module.exports = router;
./routes/about.js:
var express = require('express');
var router = express.Router();
router.get('/about', function(req, res) {
res.send('im the about page!');
});
router.post('/about', function(req, res) {
res.send('im the about page!');
});
module.exports = router;
Rewrite your router/about.js like this
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('im the about page!');
});
router.post('/', function(req, res) {
res.send('im the about page!');
});
module.exports = router;
Since in your app.js, you already declare the prefix /about at line 24, so you do not have to do it again in router/about.js
What is happening is that in app.js you have set the root for about rout as "/about" and inside "about.js" you have specified router.get('/about') again, what will result in, for accessing the about route having to use /about/about (you may try before fix it). For you to get the result that you are expecting you should use router.get(´/´) inside about.js and in app.js keep as it is app.use('/about', aboutRouter);. You can have a look at https://expressjs.com/en/guide/routing.html for more information. Regards.
I am working on a Nodejs Web application project which is based on Express Framework. I am working on creating a Sign up page. After giving the username and password the url should be redirected to profile page. In the views folder I created a file "profile.hbs". But the profile is not being recognized and I getting 404 not found. Please share your ideas on how to debug this issue.Thanks in advance.
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressHbs=require('express-handlebars');
var mongoose=require('mongoose');
var session=require('express-session');
var passport=require('passport');
var flash=require('connect-flash');
const mocha=require('mocha');
var validator=require('express-validator');
var indexRouter = require('./routes/index');
//var usersRouter = require('./routes/users');
var app = express();
mongoose.connect('mongodb://localhost:27017/shopping');
require('./config/passport');
// view engine setup
app.engine('.hbs',expressHbs({defaultLayout:'layout',extname:'.hbs'}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(session({secret:'mysupersecret',resave:false,saveUninitialized:false}));
app.use(passport.initialize());
app.use(flash());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
//app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Routing file
var express = require('express');
var router = express.Router();
var csrf=require('csurf');
var passport=require('passport');
const canine= require('../models/dogfood');
var csrfProtection=csrf();
router.use(csrfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
canine.find(function(err,docs){
var productChunks=[];
var chunkSize=3;
for(var i=0;i<docs.length;i += chunkSize){
productChunks.push(docs.slice(i,i+chunkSize));
}
res.render('shop/index', { title: 'Express',diets:productChunks});
});
});
router.get('/user/signup',function(req,res,next){
res.render('user/signup',{csrfToken:req.csrfToken()})
});
router.post('user/signup',passport.authenticate('local.signup',{
successRedirect:'user/profile',
failureRedirect:'user/signup',
failureFlash:true
}));
router.get('user/profile',function(req,res,next) {
res.render('user/profile');
});
module.exports = router;
You have a typo in the route name. It should be '/user/profile'
router.get('/user/profile', function(req,res,next) ...
In my index.ejs, there is a link which links to /signup:
Sign Up Here
This is my app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
//connect to mysql
var mysql = require('mysql');
var bodyParser = require('body-parser');
var connection = mysql.createConnection({
host:'localhost',
user: 'root',
password: '',
database: 'test'
});
connection.connect();
global.db = connection;
// all environments
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.get('/',indexRouter); //call to index site
app.get('/login', indexRouter); // call to login site
app.get('/signup', usersRouter);
module.exports = app;
this is my users.js:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
message = '';
if(req.method == "POST"){
//post data
} else {
res.render('signup.ejs');
}
});
module.exports = router;
In my index page there is a link which link which directs user to a signup page. When I click on the link which is supposed to direct me to "http://localhost:3000/signup", it shows Error 404 Not found error. I am new to NodeJs. Any help is much appreciated. Thank you.
Changed the link in index.ejs to
Sign Up Here
Added this handler to users.js
router.get('/signup',function(req,res,next){
message = '';
if(req.method == "POST"){
//post data
} else {
res.render('signup');
}
});