so I'm sort of having an issue here. I have my login route:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
require('../config/passport')(passport, LocalStrategy);
/* GET /login */
router.get('/', function(req, res) {
//you'll probably write some
res.render('login', { title: 'Please Log In' });
});
router.post('/', function(req, res) {
console.log('posting');
console.log(passport);
passport.initialize();
passport.session();
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login'
});
console.log('after');
});
module.exports = router;
my app.js:
var express = require('express'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
RedisStore = require('connect-redis')(session),
passport = require('passport'),
// LocalStrategy = require('passport-local').Strategy,
pool = require('./config/database'),
routes = require('./routes/index'),
api = require('./routes/api'),
login = require('./routes/login'),
app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session(<<redis store info>>);
app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);
app.use('/api', api);
app.use('/login', login);
...etc
and my ./config/passport.js
var pool = require('./database');
module.exports = function(passport, LocalStrategy) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
mysql.query("select * from users where id = "+id,function(err,rows){
done(err, rows[0]);
});
});
passport.use(new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) { // callback with user and password from our form
console.log('hi');
pool.query("SELECT * FROM `users` WHERE `user` = '" + username + "'",function(err,rows){
if (err)
return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
}
// if the user is found but the password is wrong
if (!( rows[0].password == password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, rows[0]);
});
}));
};
And I can't really understand why the passport config just doesn't seem to be getting processed at all. When I call passport.authenticate it's seemingly doing nothing
So, there were a few things I did to get this to work. The first is I moved the following into passport.js Having anything inside require() passport related in my route was nuts. I started without this mess, but trying to tinker had progressed to that point. Furthermore, my deserialize function incorrectly had a mysql reference instead of my pool.
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
I then just set up passport like normal in the config, and did
module.exports = passport;
Then just did this in app.js:
var passport = require('../config/passport');
then I changed my router, removed essentially the whole thing on the post function, and did:
router.post('/', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login'
}));
I learned I couldn't just call passport.authenticate. It was meant to be placed in a req handler.
Sorry for the totally insane and ambiguous question guys. Just in case any poor soul looks for this down the line, I figured I at least need to have the courtesy to talk about it.
Related
I can't understand why I'm getting an empty req.body {} in client side I get undefined or when I try to use payload = req.body.payload and console.log(payload) I get undefined on the server side and on the client side I get (chrome developer tool console)
ERROR TypeError: Cannot read properties of null (reading 'payload').
What I don't understand is the server receives the request payload(status 201) the response payload is empty, also correct me if I'm wrong the response is a JavaScript object and in the service the original payload is contained so shouldn't I get that in the response.
I have looked at many topics that have the same issue. I'm already doing things that fixed some of the issues.
I have a Content-Type application/json, I apply the app.use(json()) before I use my routes, which seemed to have been the problem with some. Yet I still get empty re.body. I have tried so many things with no luck. Am I missing something? Code snippet.
I would appreciate a point in the right direction
Thanks In Advance
PH.
service.ts
export interface Products{
_id: string,
name: string
}
#Injectable({
providedIn: 'root'
})
export class SearchService {
constructor(private http:HttpClient) { }
searchProducts(query:string){
console.log("Does it get my searchProducts");
return this.http.post<{payload: Array<Products>}>(productsUrl, {payload: query}, {
headers: new HttpHeaders({'Content-Type': 'application.json'})
}).pipe(
map(data => data.payload)
);
}
}
header.ts
sendData(event:any){
//console.log(event.target.value);
let query:string = event.target.value;
//Will match if query is nothing or only spaces
let matchSpaces:any=query.match(/\s*/);
console.log("What about match");
if(matchSpaces[0] === query){
console.log("What about query");
//.products=[];
console.log("what is in collection", this.products);
this.hasQuery = false;
return;
}
console.log("about to call service")
this.searchService.searchProducts(query.trim()).subscribe((results) =>{
console.log("does it get pass subscribe")
// this.products = results;
this.hasQuery = true;
console.log(results);
})
}
route file getProducts.js
var express = require('express');
const cors = require('cors');
var bodyParser = require('body-parser')
const Products = require('../../../liveSearch');
const { query } = require('express');
var router = express.Router();
const app = express();
router.get('/', function(req, res){
res.send('GET route on api here.');
});
/*router.post('/getproducts', function(req,res){
res.send("Trying to post")
});*/
/*app.use(cors());
var corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}*/
router.post('/getProducts', async(req, res) =>{
let payload=req.body;
//let payload= req.body.payload;
let search = await Products.find({name: {$regex: new RegExp('^'+payload+'.*',
'i')}}).exec();
//Limit search to 10
search = search.slice(0, 10);
console.log("Payload", payload)
//.log("Inside search",search);
res.status(201).json(payload) //added to see why I couldn't get
response
// res.send({payload:search});
})
server.js
const express = require('express');
const cors = require('cors');
const router = express.Router();
var bodyParser = require('body-parser');
const Products = require('./liveSearch');
const getProducts = require('.../../controllers/api/getProducts/getProducts')
//const products = require('.../../routes/products.js')
const mongoose = require('mongoose');
//mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost/productLiveSearch', {useNewUrlParser:
true, useUnifiedTopology: true, });
const db = mongoose.connection;
db.on('error', error => console.log(error));
db.once('open', () =>{ console.log('Connected to Mongoose')});
const app = express();
app.use(function(req,res,next){
res.header('Access-Control-Allow-Origin', '*');
res.header('content-type','application/json');
res.header('Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Methods','POST, GET, DELETE, PUT, OPTIONS');
res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
next();
});
app.use(cors());
var corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(express.json());
app.use(express.urlencoded({extended:true}));
// app.use(express.json({ limit: "1000mb" }));
// app.use(express.urlencoded({ limit: "1000mb", extended: true }));
app.use('/', getProducts);
app.use('/getProducts', getProducts);
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(process.env.Port|| 3000, () => {
console.log("Server has started on Port 3000");
});
I got the codes from a tutorial, seems to work fine until I made routers since I'm trying to create an E-commerce website with a login system.
This is my index.js code
const express = require('express');
const app = express();
const prodRouter = require('./server/routes/prodRouter');
const loginRouter = require('./server/routes/loginRouter');
const regRouter = require('./server/routes/regRouter');
const contRouter = require('./server/routes/contRouter');
const checkRouter = require('./server/routes/checkRouter');
const profRouter = require('./server/routes/profRouter');
const path = require('path'); const port = 3500;
app.use(express.static('public'));
app.set('views', path.join(__dirname, 'server/views'));
app.set('viewengine', 'pug');
app.use('/prod', prodRouter);
app.use('/login',loginRouter);
app.use('/reg', regRouter);
app.use('/cont',contRouter);
app.use('/check', checkRouter);
app.use('/profile',profRouter);
app.get('/', (req, res) =>{res.render('Home.pug', {}); });
app.listen(port, (err) => { // arrow function feature from ES6 if(err){ console.log(err); }
console.log(`Listening to port ${port}!`); });
and loginRouter.js
const express = require('express'); const router = express.Router();
const app = express();
const mysql = require('mysql');
const server = require('http').createServer(app);
bodyParser = require('body-parser');
const connection = mysql.createConnection({
host: 'localhost',
database: 'login',
user: 'root',
password: '',
});
users = []; connections = [];
router.get('/', (req, res) => {
res.render('login', {});
});
app.use(bodyParser.urlencoded({
extended: true
});
app.use(bodyParser.json());
connection.connect();
app.post('/', function(req, res){
var email= req.body.email;
var password = req.body.password;
connection.query('SELECT * FROM user WHERE email = ?',[email],function (error, results, fields) {
if (error) {
// console.log("error ocurred",error);
res.send({
"code":400,
"failed":"error ocurred"
})
}else{
// console.log('The solution is: ', results);
if(results.length >0){
if([0].password == password){
return res.redirect('/profile');
}else{
res.send({
"code":204,
"success":"Email and password does not match"
});
}
}else{
res.send({
"code":204,
"success":"Email does not exits"
});
}
}
});
enter code here
});
module.exports = router;
my pug form:
form#login-form(method='post')
fieldset.input
p#login-form-username
label(for='modlgn_username') Email
input#modlgn_username.inputbox(type='text', name='email', size='18', required)
p#login-form-password
label(for='modlgn_passwd') Password
input#modlgn_passwd.inputbox(type='text', name='password', size='18', required)
.remember
p#login-form-remember
label(for='modlgn_remember')
a(href='#') Forget Your Password ?
input.button(type='submit', value='Sign In')
I'm pretty sure I did something wrong with the router, because every time I login, I keep getting CANNOT POST instead of going to the profile page.
Any help would be greatly appreciated.
EDIT: I added my pug code for form.
EDIT: the problem only occurs if the login page is not the main page.
example:
login page > *logs in > profile - no problem
home page > login page > *logs in > profile - error
This is happening because you don't have an action on your form (see this article for details). When you don't have an action the form is submitted to the URL it lives at, so if you POST on your home page without an action the post will go to /home.
Change the form element to look like this:
form#login-form(method='post' action='/login')
I am building an API with Node.js, Express, MYSQL and with the help of sequelize. I am using MVC pattern.
The problem I am encountering however is the server cannot send back any http response after request. When sending a post request for example with postman, the request keeps on loading and will terminate after around 2 minutes with COULD NOT GET ANY RESPONSE exception. While this is happening, data is correctly saved in the database.
This is my AuthController user registration method:
'use strict';
// AuthController.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
const Model = require('../models/index');
const User = Model.sequelize.import('../models/user');
// Register new User.
exports.register = function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
},
function (err, user) {
if (err)
{
return res.status(500).send("There was a problem registering the user. "+err)
}
else{
// create a token
var token = jwt.sign({ id: user._id }, process.env.AUTH0_CLIENT_SECRET, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).json({ auth: true, token: token });
}
});
};
// App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
var app = express();
var indexRoutes = require('./routes/index');
var userRoutes = require('./routes/users');
var courseRoutes = require('./routes/courses');
var authRoutes = require('./routes/auth');
// view engine setup
// Currently I am not using view-templates
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors()); //enable CORS
app.use(express.static(path.join(__dirname, 'public')));
//User Routes
app.use('/', indexRoutes);
app.use('/api', userRoutes);
app.use('/api', courseRoutes);
app.use('/api/auth', authRoutes);
// 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;
//ROUTES
//auth.js
var express = require('express');
var router = express.Router();
//Require Controller Modules
var controller = require('../controllers/AuthController');
//Register new user
router.post('/register', controller.register);
router.get('/user', controller.me);
router.post('/login', controller.login);
router.get('/logout', controller.logout);
module.exports = router;
//User Model
'use strict';
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define('User', {
//id: DataTypes.INTEGER,
name: DataTypes.STRING,
email: {type: DataTypes.STRING, allowNull: false, unique: true, validate: { isEmail: {msg: "Invalid Email"} }},
password: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
return User;
};
DB Connection //in models/index.js
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(__filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
const Op = Sequelize.Op;
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
var sequelize = new Sequelize(config.database,
config.username,
config.password,
{
host: config.host,
dialect: config.dialect,
operatorsAliases: false,
}
);
//check if connection is established
sequelize
.authenticate()
.then(() => {
console.log('Database Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
I think there is something wrong I am committing or missing out something. I am experiencing this problem when sending POST REQUESTS. Data is saved in mysql table but no response is sent back.
Please assist. Thanks.
Thank you guys for trying to assist. After working around I discovered that problem was with the controller method. The way it was structured was not sending back response after data is persisted in the database.
This is how I recoded my register method in AuthController:
//Old one
// Register new User.
exports.register = function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
},
function (err, user) {
if (err)
{
return res.status(500).send("There was a problem registering the user. "+err)
}
else{
// create a token
var token = jwt.sign({ id: user._id }, process.env.AUTH0_CLIENT_SECRET, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).json({ auth: true, token: token });
}
//Rewrite:
// Register new User.
exports.register = function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
})
.then(user=>{
// create a token
var token = jwt.sign({ id: user._id }, config.secret, {
expiresIn: 86400 // expires in 24 hours
});
return res.status(200).json({ auth: true, token: token });
}).catch(err=>{
return res.status(500).send("There was a problem registering the user. "+err)
});
};
This worked for me and the code now works as expected.
I am having trouble understanding what needs to be done in order to connect to MongoDB so i can insert an Object into the database. I am new to using Express as well as MongoDB and don't have a full grasp on the both of them yet.
My app.js which was created using the standard Express setup is as follows.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ex_session = require('express-session');
var dateformat = require('dateformat');
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/contacts'
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
My index.js is as follows and what i would like to happen is when a post request is made from /mailer, a connection is made to the MongoDB in order to set up for an insert.
var express = require('express');
var router = express.Router();
var url = 'mongodb://localhost:27017/contacts';
var contacts;
/* GET home page. */
var start = function(req, res, next){
console.log("Starting!");
res.render('mailer',{});
}
router.get('/', start);
router.get('/mailer', start);
/* Post mailer Page insert into database*/
router.post('/mailer', function(req, res, next){
res.render('thanks');
console.log("Welcome to the Thank You Page");
MongoClient.connect(url, function(err, db){
if(err == NULL){
console.log("Connected to database");
// parse the body of the page and set up object to send to the
// database
}
});
});
router.get('/contact', function(req, res){
res.render('contact', {});
})
module.exports = router;
*for express ,
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DB_USERNAME+':'+DB_PASSWORD+'#'+DB_HOST+':'DB_PORT+'/'+DB_NAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server for express
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DB_HOST+':'+DB_PORT+'/'+DB_NAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
Your code is super mess,I can show your my configuration and u can refer to.
db.js
import mongoose from 'mongoose';
export default function connectDB() {
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/contacts');
mongoose.connection.once('open', function () {
console.log('mongodb connected.');
});
};
app.js
import connectDB from "db.js";
connectDB();
user.model.js
import mongoose from 'mongoose';
const schema = mongoose.Schema({
email: {type: String, required: true},
mobile: {type: String},
password: {type: String, required: true},
});
const User = mongoose.model('User', schema, 'user');
export default User;
then in your router file u can call User.find() or User.update or ...
I'm new to NodeJS, Passport, and Mongo. I'm trying to set up a basic local authentication, which is successful, however, when I try to return the entire object it returns an empty array.
My node setup:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose/');
mongoose.connect('mongodb://localhost:27017/EiData');
var Schema = mongoose.Schema;
var UserDetail = new Schema({
username: String,
password: String,
fullname: String
}, {
collection: 'userlist'
});
var UserDetails = mongoose.model('userlist', UserDetail);
var User_obj = user;
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use( express.cookieParser() );
app.use(express.session({ secret: 'plsrespond' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
So, my tactic is to set a global variable named User_Obj, and set it to be the user object that passport returns. However, I feel like it might be a scope problem, since my global variable is empty when I call it.
Here's my Passport Authentication logic:
passport.use(new LocalStrategy(function(username, password, done) {
process.nextTick(function() {
UserDetails.findOne({
'username': username,
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != password) {
return done(null, false);
}
return done(null, user);
});
});
}));
Lastly, my success/failure redirects, and where I attempt to call my User_obj global variable:
app.post('/login',
passport.authenticate('local', {
successRedirect: '/loginSuccess',
failureRedirect: '/loginFailure'
})
);
app.get('/loginFailure', function(req, res, next) {
res.send('Invalid code!');
});
app.get('/loginSuccess', function(req, res, next) {
res.json(User_obj)
});