cannot POST / Nodejs - javascript

Please help me solve the error I've been trying hard to solve it for a long time.Because of this I'm not able to add data to my database as well.
Any help would be highly appreciated.
This is my index.js code
const express = require('express');
const app = express();
const routes = require('./routes');
const path = require('path');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const session = require('express-session');
const auth = require('./routes/auth');
const {
con,
sessionStore
} = require('./config/db');
const fs = require('fs');
require('dotenv').config({
path: path.join(__dirname, '.env')
});
const port = process.env.PORT || 3000;
// parse application/json
app.use(bodyParser.json())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
//static files
app.use(express.static('public'))
app.use('/css' , express.static(__dirname + 'public/css'))
app.use('/imgs' , express.static(__dirname + 'public/imgs'))
var sess = {
secret: 'keyboard cat',
store: sessionStore,
cookie: {
httpOnly: false,
},
resave: false,
saveUninitialized: false
}
app.use(session(sess));
app.use(fileUpload());
//set views
app.set('view engine' , 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(require('connect-flash')());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('/', (req,res) =>{
res.render('index22')
})
app.get('/login', (req, res) => {
res.render('login');
});
let s;
const loginRequired = (req, res, next) => {
if (req.session.username) {
s = req.session;
next();
} else {
res.redirect('/auth/login');
}
}
app.get('/new', loginRequired, routes.new);//call for main index page
app.post('/new', loginRequired, routes.new);//call for signup post
app.get('/show/:username', loginRequired, routes.show);
app.use('/auth', auth);
app.listen(port, () => console.log(`listening on http://${process.env.HOST}:${port}`));
here's my routes.js code
const {
con,
sessionStore
} = require('./config/db');
exports.new = function(req, res){
message = '';
if(req.method == "POST"){
const post = req.body;
const username= post.username;
const title= post.title;
const state= post.state;
const category= post.category;
const description= post.description;
if (!req.files)
return res.status(400).send('No files were uploaded.');
const file = req.files.uploads;
const img_name=file.name;
if(file.mimetype == "images/jpeg" ||file.mimetype == "images/png"||file.mimetype == "images/gif" ){
file.mv('public/imgs/uploads/'+file.name, function(err) {
if (err)
return res.status(500).send(err);
const sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES ('" + username + "','" + title + "','" + state + "','" + category + "','" + img_name + "','" + description + "')";
const query = con.query(sql, function(err, result) {
res.redirect('show/'+result.insertUsername);
});
});
} else {
message = "This format is not allowed , please upload file with '.png','.gif','.jpg'";
res.render('new.ejs',{message: message});
}
} else {
res.render('new');
}
};
exports.show = function(req, res){
let message = '';
const username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
if(result.length <= 0)
message = "show not found!";
res.render('show.ejs',{data:result, message: message});
});
};
And here's an part of my new.ejs code
<body>
<h1 class="mt-5" id="h1">New Post</h1>
<hr class="w-50">
<div class="container mt-3">
<form action="/" method="POST" class="was-validated" enctype="multipart/form-data">
<% if (message.length > 0) { %>
<div class="alert alert-success col-sm-12"><%= message %></div>
<% } %>
<div class="row">
<div class="col-6">
<select name="state" class="custom-select mb-3">
<option>Select Sate</option>
<option value="Sikkim">Sikkim</option>
<option value="Manipur">Manipur</option>
<option value="Mizoram">Mizoram</option>
</select>
</div>
please help me solve this error it's very important.
Thank you

Your index.js file doesn't contain a POST Method for the route "/". You can use the below example to add one:
app.post('/',function(req,res){
//Your function code
});

Related

Login mechanism using jwt / mysql / api for a website

I'm trying to make a login mechanism with jwt but as I'm a newbie, I'm not sure if I'm doing right.
I already made my server.js which looks like this :
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const path = require('path');
require('dotenv').config();
var cors = require('cors');
const app = express();
const port = process.env.PORT || 8600;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
});
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));
const adRoutes = require('./routes/adRoutes.js');
app.use('/Advertisements', adRoutes);
const comRoutes = require('./routes/comRoutes.js');
app.use('/Companies', comRoutes);
const userRoutes = require('./routes/userRoutes.js');
app.use('/Users', userRoutes);
const appRoutes = require('./routes/appRoutes.js');
app.use('/Applications', appRoutes);
const appAuth = require('./routes/loginRoutes.js');
let refreshTokens = [];
app.use('/auth', appAuth);
app.get('/api', authenticateToken, (req, res) => {
res.json(posts.filter(post => post.username === req.user.name))
});
app.post('/auth/token', (req, res) => {
const refrechToken = req.body.token;
if (refrechToken == null) return res.sendStatus(401);
if (!refreshTokens.includes(refrechToken)) return res.sendStatus(403);
jwt.verify(refrechToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
const accessToken = generateAccessToken({ name: user.name });
res.json({ accessToken: accessToken });
}
)
});
app.post('/auth/login', (req, res) => {
const email = req.body.email;
const password = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
const accessToken = generateAccessToken({ email: email });
const refreshToken = jwt.sign(email, process.env.REFRESH_TOKEN_SECRET);
refreshTokens.push(refreshToken);
res.json({ accessToken: accessToken, refreshToken: refreshToken });
});
app.delete('/auth/logout', (req, res) => {
refreshTokens = refreshTokens.filter(token => token !== req.body.token);
res.sendStatus(204);
});
function generateAccessToken(email) {
return jwt.sign(email, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1800s' });
}
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.listen(port)
And I have a login mechanism that works on Postman but without jwt like this :
const express = require('express');
const router = express.Router();
const path = require('path');
const CryptoJS = require('crypto-js');
const UserController = require('../controllers/userController.js');
var con = require("../config.js");
const { log } = require('console');
router.get('/', function(request, response) {
response.sendFile(path.join(__dirname, '../../front', 'login.html'));
});
router.post('/register', (req, res) => {
const hashedPassword = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
req.body.password = hashedPassword;
UserController.create(req, res);
});
router.post('/login', function(req, res) {
const email = req.body.email;
const hashedPassword = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
email_ = "\"" + email + "\"";
password_ = "\"" + hashedPassword + "\"";
if (email == "" || hashedPassword == ""){
res.send('Please enter Email and/or Password !');
}
else{
var sql = "SELECT * FROM User WHERE email = " + email_;
con.query(sql, function (err, result) {
if (err) throw err;
if (result.length == 0){
res.send('Incorrect Email !');
}
else{
if (result[0].password == hashedPassword){
req.session.email = result[0].email;
res.send('Login successful!');
}
else{
res.send("Incorrect Password !");
}
}
});
}
});
router.get('/check', function(req, res) {
if (req.session.email) {
console.log(req.session.email);
res.send('Logged in');
} else {
res.send('Not logged in');
}
});
router.get('/logout', function(req, res) {
req.session.destroy();
res.send('Logout successful!');
});
I want to 1. login with token, 2. auto-filled profile using the token and 3. logout system
So that I could make them and that it works on the website, let me know not exact codes but just a mechanism or functions that I need please.
Here's my config.js if you need :
const mysql = require("mysql");
const con = mysql.createConnection({
host: "localhost",
user: "username",
password: "password",
database: "DB name",
port: "port"
});
con.connect((err) => {
if(err)
{
console.warn("Error in connection: " + err.message);
}
});
module.exports = con;

Cannot POST /login - POST http://localhost:3000/login 404 (Not Found)

I'm serving my login form but for some reason can't POST to login and actually log in. I think it has something to do with my route folders, but I've tried several iterations of the routing and can't seem to figure it out. I keep receiving error POST http://localhost:3000/login 404 (Not Found).
My app runs on port 3000.
CRUD path: "Routes" folder-> artists.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const Artist = require('../models/artist');
const catchAsync = require('../utils/catchAsync');
const ExpressError = require('../utils/ExpressError');
/* lists artists from database */
router.get('/', async (req, res) => {
const artists = await Artist.find({});
res.render('artists/index', { artists })
});
router.get('/new', (req, res) => {
res.render('artists/new');
});
router.get('/login', (req, res) => {
res.render('artists/login');
})
/* shows specific artists that exist in database */
/* link - show.ejs */
router.get('/:id', catchAsync(async(req, res,) => {
const artist = await Artist.findById(req.params.id);
if (!artist) {
req.flash('error', 'Cannot find that Artist');
return res.redirect('/artists');
}
res.render('artists/show', { artist });
}));
/* artist edits form*/
router.get('/:id/edit', catchAsync(async (req, res) => {
const artist = await Artist.findById(req.params.id);
if (!artist) {
req.flash('error', 'Cannot find that Artist');
return res.redirect('/artists');
}
res.render('artists/edit', { artist });
}))
router.put('/:id', catchAsync(async (req, res) => {
const { id } = req.params;
const artist = await Artist.findByIdAndUpdate(id, { ...req.body.artist });
res.redirect(`/artists/${artist._id}`);
}))
/* creating a new artist */
router.post('/new', catchAsync(async(req, res) => {
try {
const { email, username, password, location, genre, about, size } = req.body;
const artist = new Artist({ email, username, location, genre, about, size });
const registeredArtist = await Artist.register(artist, password);
req.flash('success', 'Successfully signed up!');
res.redirect(`/artists/${artist._id}`)
} catch (e) {
req.flash('error', 'Sorry, an artist with that email already exists');
res.redirect('/artists');
}
}));
/** Where I'm encountering my error **/
router.post('/login', passport.authenticate('local', { failureFlash: true, failureRedirect: '/login' }), (req, res) =>{
req.flash('success', 'Welcome back!');
res.redirect('/artists');
})
/* delete a post */
router.delete('/:id', catchAsync(async (req, res) => {
const{ id } = req.params;
await Artist.findByIdAndDelete(id);
res.redirect('/artists');
}))
router.all('*', (req, res, next) => {
next(new ExpressError('Page Not Found', 404))
})
router.use((err, req, res, next) => {
const { statusCode = 500, message = 'Something went wrong' } = err;
res.status(statusCode).render('error');
})
module.exports = router;
Here's the ejs form w/ path: "Views" folder-> "artists" folder-> login.ejs
<% layout('layouts/boilerplate')%>
<div class="container d-flex justify-content-center align-items-center mt-5">
<div class="row">
<div class="col-md-6 offset-md-3 col-xl-4 offset-xl-4">
<div class="card shadow">
<img src="https://images.unsplash.com/photo-1571863533956-01c88e79957e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1267&q=80"
alt="" class="card-img-top" />
<div class="card-body">
<h5 class="card-title">Login</h5>
<form action="/login" method="POST" class="validated-form" novalidate>
<div class="mb-3">
<label class="form-label" for="artist[username]">Username</label>
<input class="form-control" type="text" id="artist[username]" name="artist[username]" required autofocus>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label class="form-label" for="artist[password]">Password</label>
<input class="form-control" type="password" id="artist[password]" name="artist[password]" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<button class="btn btn-success btn-block">Login</button>
</form>
</div>
</div>
</div>
</div>
</div>
Below is my app.js to display all routes. I also have "users" and "events". Only Users and Artists can login.
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const ejsMate = require('ejs-mate');
const catchAsync = require('./utils/catchAsync');
const methodOverride = require('method-override');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const session = require('express-session');
const Artist = require('./models/artist');
const Event = require('./models/event');
const User = require('./models/user');
const flash = require('connect-flash');
const eventRoutes = require('./routes/events');
const userRoutes = require('./routes/users');
const artistRoutes = require('./routes/artists');
const dbUrl = process.env.DB_URL || 'mongodb://localhost:27017/macro-tickets';
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const app = express();
app.engine('ejs', ejsMate);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
/* method override allows to serve put requests into the database */
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')))
const sessionConfig = {
secret: 'thisshouldbeabettersecret!',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}
app.use(session(sessionConfig))
app.use(flash());
app.use((req, res, next) => {
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
})
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.use(new LocalStrategy(Artist.authenticate()));
passport.serializeUser(User.serializeUser());
passport.serializeUser(Artist.serializeUser());
passport.deserializeUser(User.deserializeUser());
passport.deserializeUser(Artist.deserializeUser());
app.use('/events', eventRoutes)
app.use('/users', userRoutes);
app.use('/artists', artistRoutes)
app.listen(3000, () => {
console.log('Serving on port 3000')
})
The form is POSTing to '/login' but nothing is going through. Any ideas what I'm doing wrong?
If to use this router you are calling it with
app.use("/your-route", require("../routes/artists.js")
the correct address would be http://localhost:3000/your-route/login.
In your case it seems I can think what you do:
app.use("/artists", require("../routes/artists.js")
then the post request would be http://localhost:3000/artists/login.
You can try this,
Update this in your app.js file
app.use(require('./routes/artists'))
then your request link will be like http://localhost:3000/login

IF Statement is setting a session attribute in NODE js and express

I am trying to do a log in page for a Uni project and am having difficulty as when trying to redirect user based on an access level the if statement is setting the Access Role before the function and so all traffic when first logged in gets redirected to the Admin page, refreshing the page makes the code work properly as that it when the code that gets the details from the database has finished running... Any help would be great thanks!
LogInController
const session = require('express-session');
var Login = require('../models/Login');
exports.checksLogin = (req, res) => {
// Implement this method using the pupil model
console.log(req.originalUrl + "POST Received with query: ", req.body)
const {Email, Pswd} = req.body
Login.checkLogin(Email, Pswd)
if(session.AccessRole='Admin'){
res.redirect('/admin')
}
else{
}
}
Login.js (Models)
exports.checkLogin = (Email, Pswd) => {
var database = require('../dbConfig');
database.then(con => {
con.query("SELECT * FROM Pupils WHERE Email = '" + Email + "'AND Pswd= '" + Pswd + "'").then(([rows]) => {
//console.log(rows)
if(rows.length>0){
session.LoggedIn=true;
session.FirstName=rows[0].FirstName
session.LastName=rows[0].LastName
session.Email=rows[0].Email
session.CourseCode=rows[0].CourseCode
session.Pswd=rows[0].Pswd
session.AccessRole='Student'
console.log(session.Loggedin+ '1')
}
else {
con.query("SELECT * FROM Staff WHERE Email = '" + Email + "'AND Pswd= '" + Pswd + "'").then(([rows]) => {
console.log(rows)
session.LoggedIn=true;
session.staffID=rows[0].staffID
session.FirstName=rows[0].FirstName
session.LastName=rows[0].LastName
session.Email=rows[0].Email
session.Role=rows[0].Role
session.Pswd=rows[0].Pswd
if(session.Role='Admin'){
console.log(`Admin`)
session.AccessRole='Admin'
}else{
session.AccessRole='Staff'
}
})
}
})
})
}
index.js
const express = require('express');
const app = express();
const path = require('path');
const exphbs = require('express-handlebars');
var session = require('express-session');
var bodyParser = require('body-parser');
// Middlewares
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars')
app.use(express.urlencoded({extended: true}))
// Client routes
app.get('/', (req, res) => res.render('index'));
app.use('/admin', require('./routes/Admin'));
app.use('/login', require('./routes/Login'));
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
const PORT= process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Started on port ${PORT} `));
Login.js (Routes)
const express = require('express');
const router = express.Router();
var Login_controller = require('../controllers/LoginController');
// Use the login.handlebars template
router.get('/', (req, res) => res.render("login"));
// CRUD routes
router.post("/submit-login", Login_controller.checksLogin);
module.exports = router;
Admin.js
const express = require('express');
const session = require('express-session');
const router = express.Router();
var pupils_controller = require('../controllers/PupilsController');
var staff_controller = require('../controllers/StaffController')
// Use the login.handlebars template
router.get('/', (req, res) => {
console.log(session.LoggedIn)
if(session.AccessRole=='Admin'){
res.render("admin")
}
else{
console.log(`No Entry`)
res.redirect('/')
}
});
// CRUD routes
router.post('/create-pupil', pupils_controller.createPupil);
router.post('/delete-pupil', pupils_controller.deletePupil);
router.post('/create-staff', staff_controller.createStaff)
module.exports = router;
login.handlebars
<p> Log In </p>
<form method="POST" action="/login/submit-login">
<label for="Email">Email</label><br>
<input type="text" name="Email" /><br>
<label for="Pswd">Password</label><br>
<input type="text" name="Pswd" /><br>
<input type="submit" />
</form>
Using a MYSQL database, Node js and express
Thanks
Please note that the IF statement here must have double equal sign to compare, instead of that you are doing an assignation
const session = require('express-session');
var Login = require('../models/Login');
exports.checksLogin = async (req, res) => {
// Implement this method using the pupil model
console.log(req.originalUrl + "POST Received with query: ", req.body)
const {Email, Pswd} = req.body
await Login.checkLogin(Email, Pswd)
if(session.AccessRole == 'Admin') {
res.redirect('/admin')
} else {
}
}

TypeError: Cannot read property 'insertUsername' of undefined

When I try to submit the login form created by new.ejs file, I am redirected to a page with an error, part of which says
Cannot read property 'insertUsername' of undefined
This message also appears in the console. What is happening and how can I fix it?
here's my idex.js
const express = require('express');
const app = express();
const routes = require('./routes');
const path = require('path');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const session = require('express-session');
const auth = require('./routes/auth');
const {
con,
sessionStore
} = require('./config/db');
const fs = require('fs');
require('dotenv').config({
path: path.join(__dirname, '.env')
});
const port = process.env.PORT || 3000;
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
// parse application/json
app.use(bodyParser.json());
//static files
app.use(express.static('public'))
app.use('/css' , express.static(__dirname + 'public/css'))
app.use('/imgs' , express.static(__dirname + 'public/imgs'))
var sess = {
secret: 'keyboard cat',
store: sessionStore,
cookie: {
httpOnly: false,
},
resave: false,
saveUninitialized: false
}
app.use(session(sess));
app.use(fileUpload());
//set views
app.set('view engine' , 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(require('connect-flash')());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.get('/', (req,res) =>{
res.render('index22')
});
app.get('/login', (req, res) => {
res.render('login');
});
let s;
const loginRequired = (req, res, next) => {
if (req.session.username) {
s = req.session;
next();
} else {
res.redirect('/auth/login');
}
};
app.get('/new', loginRequired, routes.new);//call for main index page
app.post('/', loginRequired, routes.new);//call for signup post
app.get('/show/:username', loginRequired, routes.show);
routes.js
const {
con,
sessionStore
} = require('./config/db');
exports.new = function(req, res){
message = '';
if(req.method == "POST"){
const post = req.body;
const username= post.username;
const title= post.title;
const state= post.state;
const category= post.category;
const description= post.description;
if (!req.files)
return res.status(400).send('No files were uploaded.');
const file = req.files.uploaded_image;
const img_name=file.name;
if(file.mimetype == "image/jpeg" ||file.mimetype == "image/png"||file.mimetype == "image/gif" ){
file.mv('public/imgs/uploads/'+file.name, function(err) {
if (err)
return res.status(500).send(err);
var sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES ('" + username + "','" + title + "','" + state + "','" + category + "','" + img_name + "','" + description + "')";
var query = con.query(sql, function(err, result) {
res.redirect('show/'+result.insertUsername);
});
});
} else {
message = "This format is not allowed , please upload file with '.png','.gif','.jpg'";
res.render('new.ejs',{message: message});
}
} else {
res.render('new');
}
};
exports.show = function(req, res){
let message = '';
var username = req.params.username;
const sql="SELECT * FROM `nt_data` WHERE `username`='"+username+"'";
con.query(sql, function(err, result){
if(result.length <= 0)
message = "show not found!";
res.render('show.ejs',{data:result, message: message});
});
};
You only get results from SELECT queries, not INSERT, UPDATE, or DELETE. Just use the username in the username variable for the redirect.
Also, use a placeholder for the variable data in the query.
var sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES ?";
var query = con.query(sql, [username, title, state, category, img_name, description], function(err) {
if (!err) {
res.redirect('show/' + username);
}
});

req.session is undefined in Node?

I already looked at the other answers for similar questions, yet none of them worked for me. I two pieces of code, one to test that cookies were working(cookieTest.js), and one to actually use them(users.js). I tried moving the app.use() statements for the session middleware and the cookie middleware to no avail. Any ideas on how to fix this?
users.js
//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect("MY_DB");
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')
var User = require('../models/user.js');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var uuid = require('node-uuid');
var cookieParser = require('cookie-parser');
//Express Setup
var express = require('express');
var router = express.Router();
var app = express();
var expressValidator = require("express-validator");
var session = require('express-session');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: '_secret_', cookie: { maxAge: 60 * 60 * 1000 }, saveUninitialized: false, resave: false}))
//Routes
router.get('/register', function(req, res){
res.sendFile(appDir + "/views/register.html");
})
router.post('/register', function(req, res) {
req.check('name', 'Name must be Filled in').notEmpty();
req.check('email', 'Email must be Filled in').notEmpty();
req.check('email', "Invalid Email").isEmail();
req.check('password', 'Password Field must be Filled in').notEmpty();
req.check('password', 'Passwords do not Match').equals(req.body.password2)
var errors = req.validationErrors();
if(errors) res.send(errors)
else{
var newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
info: req.body.user_bio
});
User.createUser(newUser, function(err, user){
if(err) throw err;
});
res.redirect('../')
}
})
router.get('/login', function(req, res){
res.sendFile(appDir + "/views/login.html");
})
router.post('/login', function(req, res){
var email = req.body.email;
var candidatePass = req.body.password;
User.findOne({ 'email': email }, 'password id', function (err, user) {
if (err) return handleError(err);
User.checkPassword(candidatePass, user.password, function(err, isMatch){
if(err) throw err;
if(!isMatch) res.end('Password Incorrect!');
else{
req.session.userId = user.id;
res.redirect('../');
}
})
})
})
//Exports
module.exports = router;
When I run this I get the error TypeError: Cannot set property 'userId' of undefined, which means that req.session is undefined. However, when I run this, it works fine
var express = require('express');
var session = require('express-session');
var app = express();
var uuid = require('node-uuid');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Use the session middleware
app.use(session({
secret: 'jaredasch',
cookie: { maxAge: 60 * 60 * 1000 },
saveUninitialized: false,
resave: false
}))
// Access the session as req.session
app.get('/', function(req, res, next) {
var sess = req.session
if (sess.uuid) {
res.setHeader('Content-Type', 'text/html');
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
res.write('<form method = \'POST\'action = \'/\'><button type = \'submit\'></form>');
res.end()
} else {
sess.uuid = uuid.v4();
res.setHeader('Content-Type', 'text/html');
res.write('Set Up Session \n')
res.write('<p>Session UUID: ' + sess.uuid + '</p>');
res.end('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>');
}
})
app.post('/', function(req,res){
req.session.destroy(function(err) {
if(err) throw err;
console.log('Session Destroyed')
})
res.redirect('/');
})
app.listen(3000, function(){
console.log('Listening on Port 3000')
});
Why does this work and the one above not, and how could I fix the one above? How would you reccomend fixing such an issue?
Try using app.use(cookieParser("_secret_")); so that its the same secret as with Express

Categories