Why Am getting the request-body content as empty? - node.js

when i submit the register form ,the data from that register page should be posted on the console.. and I try to print that result using "req.body.Username" , it says undefined and when i view the req in console. The body seems to be an empty set like " {} ", how to post my form details in body to view in console and how to get rid of that "undefined" error?
app.js
const express = require('express');
const flash = require('connect-flash');
const path = require('path');
const request = require('request')
const expressValidator = require('express-validator');
const authRoutes = require('./routes/auth-routes');
const session = require('express-session');
const passport = require('passport');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const db = require('./config/db');
const registerc = require('./registerc');
const loginc = require('./loginc');
const registerRoute = require('./routes/register');
const fs = require('fs');
// const request = require('./modules/module1')
const app = express();
// set view engine
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// set up routes
app.use('/auth', authRoutes);
app.use('', registerRoute);
// create home route
app.get('/', (req, res) => {
res.render('home');
res.render('mycourses', {
final1: final1
});
res.render('recent', {
final2: final2
});
});
// fetching course details
request(options, function (error, response, result) {
if (error) throw new Error(error);
// console.log(result);
// final1 = JSON.stringify(result)
final1 = JSON.parse(result);
// console.log(final1);
});
// fetching User recent Activity
request(options, function (error, response, result) {
if (error) throw new Error(error);
// console.log(result);
final2 = JSON.parse(result);
// console.log(final2);
// console.log(final2.length)
});
app.use(session(
{
secret : 'secret',
saveUninitialised : true,
resave : true
}
));
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(flash());
// app.use(function(res,req,next){
// res.locals.success_msg = req.flash('success_msg');
// res.locals.error_msg = req.flash('error_msg');
// res.locals.error = req.flash('error');
// next();
// })
// app.post('/api/register',registerc.register);
// app.post('/api/login', loginc.login);
app.listen(3000, () => {
console.log('app now listening for requests on port 3000');
});

In your app.js, update the register auth from
app.use('', registerRoute);
To
app.use('/soemRoute', registerRoute);

Related

Problem In running code for Token-based authentication-passport using NodeJS & ExpressJS

app.js
const express = require('express');
const path = require('path');
const logger = require('morgan');
const app = express();
// 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(express.static(path.join(__dirname, 'public')));
app.use('/dishes', dishRouter);
app.use('/dishes/:dishId', dishRouter);
module.exports = app;
authenticate.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('./models/user');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const jwt= require('jsonwebtoken');
const config = require('./config.js');
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
exports.local = passport.use(new LocalStrategy(User.authenticate()));
exports.getToken=function(user){
return jwt.sign(user, config.secretKey,
{expiresIn: 3600});
};
const opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.secretKey
};
exports.jwtPassport = passport.use(new JwtStrategy(opts,
(jwt_payload, done)=>{
User.findOne({_id:jwt_payload._id}, (err, user)=>{
if(err){
return done(err, false);//(optional params)callback that passport will pass your startegy here
}
else if(user) {
return done(null, user);
}
else{
return done(null, false);//if we want we can create a new user
}
});
}));
exports.verifyUser = passport.authenticate('jwt', { session: false });
config.js
module.exports={
'secretKey':'12345-67890-09876-54321',
'mongoUrl':'mongodb://localhost:27017/conFusion'
}
dishRouter.js
const express = require('express');
const bodyParser = require('body-parser');
const authenticate = ('../authenticate');//higher level folder
const Dishes = require('../models/dishes');
const dishRouter = express.Router();
dishRouter.use(bodyParser.json());
dishRouter.route('/')
.get((req,res,next) => {
//performing find operation
Dishes.find({}).then((dishes)=>{
res.statusCode = 200;
res.setHeader('Content-Type','application/json');
//take a input as a json string & send it back to the client(json response)
res.json(dishes);
},(err)=>next(err)).catch((err)=>next(err));
})
.post(authenticate.verifyUser, (req, res, next) => {
Dishes.create(req.body).then((dishes)=>{
console.log('dish created...',dishes);
res.setHeader('Content-Type','application/json');
res.json(dishes);
},(err)=>next(err)).catch((err)=>next(err));
})
.put(authenticate.verifyUser,(req, res, next) => {
res.statusCode = 403;
res.end('PUT operation not supported on /dishes');
})
.delete(authenticate.verifyUser,(req, res, next) => {
Dishes.remove({}).then((resp)=>{
res.statusCode = 200;
res.setHeader('Content-Type','application/json');
//take a input as a json string & send it back to the client(json response)
res.json(resp);
},(err)=>next(err)).catch((err)=>next(err));
});
// Other routes
module.exports = dishRouter;
While Running the code I got the following Error
While running this code I got Error: Route.post() requires a callback function but got a [object Undefined]
at Route. [as post] (D:\EDUCATION\nodejs\node-express generator\conFusionServer\node_modules[4mexpress[24m\lib\router\route.js:202:15)
at Object. (D:\EDUCATION\nodejs\node-express generator\conFusionServer\routes\dishRouter.js:21:4) and Error app.js:28 th line I am unable fix this error anyone can help me to fix this error
There's a missing require in dishRouter.js; line 4.
Fix:
const authenticate = require('../authenticate');

Get "undefined" for req.session in nodejs

Noob here, and I tried to have a session to do the login attempt count in nodejs, but it seem the session is not declared in route as it just show undefined when i console.log it.
Below is my code :
Server.js
var express = require('express');
var session = require('express-session');
var cors = require('cors');
var bodyParser = require("body-parser");
var app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(cors());
app.use(session({ resave: false, saveUninitialized: true, secret: 'onemonkey', cookie: { secure: false }}));
app.use(bodyParser.urlencoded({
extended: false
}));
var Users = require('./Routes/Users');
app.use('/users',Users);
app.listen(port,function(){
console.log("Server is running on port: "+port);
});
in users.js
var express = require('express');
var users = express.Router();
var database = require('../Database/database');
var cors = require('cors')
var jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
//var request = require('request');
var token;
users.use(cors());
users.post('/login', function(req, res) {
var appData = {};
var email = req.body.email;
var password = req.body.password;
let someRows, otherRows;
let token;
var databaseQuery = new database.DatabaseQuery();
databaseQuery.beginTransaction()
.then (() => {
return databaseQuery.query('SELECT * FROM users WHERE email = ? AND status = ?', [email, 'active'])
})
.then( rows => {
someRows = rows;
if (someRows.length > 0) {
bcrypt.compare(password, someRows[0].password).then(function(ret) {
// res == true
if(ret){
//when validate successfully
}else{
console.log(req.session[email]);
req.session[email] = req.session[email] + 1;
req.session.save();
console.log('--------login-----');
console.log(req.session[email]);
if(req.session[email] == 3){
databaseQuery.query('update users set status=? where email=?',['block',email])
.then( rows => {
otherRows = rows;
var user_status = {
contact_id : someRows.insertId,
remark : "3 times login attempt fail",
status : "block",
edit_by : "SYSTEM"
}
return databaseQuery.query( 'INSERT INTO user_status_detail SET ?', [user_status] );
}).then ( rows =>{
appData.error = 1;
appData["data"] = "Email account blocked";
req.session[email] = null;
req.session.save();
res.status(200).json(appData);
return databaseQuery.commit();
}, err => {
return databaseQuery.close.then( () => { throw err; } )
})
}else{
//record not match
}
}
});
}else {
//account not exist
}
})
.catch( err => {
//err handling
} )
});
module.exports = users;
I tried to store the count in req.session[email] in user.js, and block the email once the count equal to 3. However, it not storing the count and showing undefined every time i tried to login which wrong password.
Highly appreciate your advise on it.
add these lines to the top :
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

Cannot read property 'end' of undefined - MySQL , NodeJS

I want to show you my error with NodeJS and MySQL.
Error is at line 45 of app.js
Cannot read property 'end' of undefined
at ServerResponse.<anonymous> (/usr/my_server/app.js:45:24)
It happen when I call a request from 'addReferFriend.js' file.
I link here the two files that I am using.
app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql= require('mysql2');
var http = require('http');
var app = express();
var addReferFriend = require('./addReferFriend');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(async function(req, res, next) {
try {
if( req.dbConnection ) {
// ensure that req.dbConnection was not set already by another middleware
throw new Error('req.dbConnection was already set')
}
let connection = mysql.createConnection({
host: 'xx',
user: 'xx',
password: 'xx',
database: 'xx'
});
res.on("finish", function() {
// end the connection after the resonponse was send
req.dbConnection.end()
});
// wait for the connection and assign it to the request
req.dbConnection = await connection.connect();
next();
} catch(err) {
next(err);
}
});
app.use('/api/addReferFriend', addReferFriend);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
var server = http.createServer(app);
server.listen(3955);
addReferFriend.js:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.post('/', function(req, res, next) {
var uid = req.body.uid;
var friendReferCode = req.body.friendReferCode;
var sqlCheckIfExist = "SELECT my_refer FROM hub_user WHERE my_refer = '" + friendReferCode + "'";
var sqlCodeCheckSameAsMine = "SELECT my_refer FROM hub_user WHERE uid = '" + uid + "'";
function checkIfUserCodeExist() {
return req.dbConnection.query(sqlCheckIfExist)
.then(([rows, fields]) => {
if (rows == 0) {
console.log("Non esiste!")
return res.send(JSON.stringify({
"status": 500,
"response": "codeNotExist"
}));
}
console.log("Esiste!")
return checkIfCodeIsSameAsMine(connection)
})
}
function checkIfCodeIsSameAsMine() {
return req.dbConnection.query(sqlCodeCheckSameAsMine)
.then(([rows, fields]) => {
if (rows == friendReferCode) {
console.log("Codice uguale!")
return res.send(JSON.stringify({
"status": 500,
"response": "sameCodeAsMine"
}));
}
console.log("Codice non uguale!")
})
}
checkIfUserCodeExist()
.catch(next)
});
module.exports = router;
I have no idea how fix this type of problem. It happen when I call the checkIfUserCodeExist() and it doesn't join into the function and it gives directly the error. I can't print any of console.log because it break.
Hope that somebody can help me with this issue.
Thanks in advance for the help,
Michele.
it seems to be req.dbConnection.end() the problem... the object dbConnection is undefined.
is it possible that the connection is closed first for some reason? so the point to closing connection is not correct?

request body parameters are undefined in nodejs busboy

I am using formdata to have multipart data and for that i am using busboy-body-parser. But somehow the body is not accessible and the value is undefined.
app.js
var express = require('express');
var mongoose = require('mongoose');
var Uploader = require('s3-image-uploader');
var config = require('./config.js');
var busboyBodyParser = require('busboy-body-parser');
var uploader = new Uploader({
aws: {
key: config.awsKey,
secret: config.awsSecret
},
websockets: false
});
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var multer = require('multer');
// var uuid = require("uuid");
var app = express();
var morgan = require('morgan');
var path = require('path');
var port = process.env.PORT || 3000;
var foodtrucklist = require('./controller/foodtrucklist.js');
var login = require('./controller/login.js');
var itemInfo = require('./controller/item_info.js');
var review = require('./controller/reviews.js');
var popularitems = require('./controller/popularitems.js');
var foodtruck = require('./model/datafoodtruck');
var truckData = require('./model/foodtruck.js');
var webToken = require('./controller/webtoken.js');
var userprofile = require('./controller/userprofile.js');
var notificationdata = require('./model/dataNotifications.js');
var notification = require('./controller/notifications.js');
var foodtruckItemList = require('./controller/item_list_foodtruck.js');
var orderList = require('./controller/orders_foodtruck.js');
var ordermanagement = require('./controller/ordermanagement.js');
var db = mongoose.connect(config.local_mongo_url);
mongoose.connection.once('connected', function() {
console.log("Connected to database")
// foodtruck.save();
// notificationdata.save();
});
app.use(bodyParser.urlencoded({
extended: true
}));
// app.use(multipartyMiddleware);
app.post('/testupload', function(req, res) {
// var file = req.files.file;
// var stream = fs.creatReadStream(req.files.file.path);
// return s3fsImpl.writeFile(file.originalFilename, stream).then(function() {
// console.log(file);
// return;
// fs.unlink(file.path, function(err) {
// if (err) console.error(err);
// res.json({
// status: '200',
// message: 'uploaded'
// });
// });
// })
res.connection.setTimeout(0);
uploader.upload({
fileId: 'someUniqueIdentifier',
bucket: 'quflip',
source: './public/images/food-3-mdpi.png',
name: 'food-3-mdpi.png'
},
function(data) { // success
// console.log('upload success:', data);
res.json({
status: '200',
message: 'image uploaded successfully'
});
},
function(errMsg, errObject) { //error
// console.error('unable to upload: ' + errMsg + ':', errObject);
res.json({
status: '404',
message: 'image is not uploaded successfully'
});
});
});
// app.use('/public/images', express.static(__dirname + '/public/images'));
app.use(morgan('dev'));
// app.use(bodyParser.urlencoded({extended: true}));
app.get('/foodtrucklist', foodtrucklist);
app.post('/itemInfo', itemInfo.itemInfo);
app.post('/likeitem', itemInfo.likeItem);
app.get('/popularitems', popularitems);
app.post('/notification', notification);
app.post('/submitreview', review.addreview);
app.post('/getreview', review.getReview);
app.post('/addOrder', ordermanagement.addOrder);
app.post('/orderHistory', ordermanagement.orderHistory);
app.post('/cancelOrder', ordermanagement.cancelOrder);
app.post('/getOrderStatus', ordermanagement.getOrderStatus);
app.post('/rateOrder', ordermanagement.rateOrder);
app.post('/updateUser', userprofile.updateUser);
app.post('/getUserInfo', userprofile.getUserInfo);
app.post('/createToken', webToken.createToken);
app.post('/checkToken', webToken.checkToken);
app.post('/itemList', foodtruckItemList.getItemList);
app.post('/updateItemStatus', foodtruckItemList.updateItemStatus);
app.post('/addItem', foodtruckItemList.addItem);
app.post('/deletItem', foodtruckItemList.deletItem);
app.post('/orderlist', orderList.getOrderList);
app.post('/statusOrderlist', orderList.getStatusOrderList);
app.post('/updateorder', orderList.updateOrder);
app.use(bodyParser.urlencoded({extended: false}));
app.use(busboyBodyParser({ limit: '50mb' }));
app.post('/login', function(req,res) {
console.log("body" + req.body.email_id + "file" + req.files);
});
app.listen(port, function() {
console.log('express listining on port' + port);
});
so, how can I access body parameters even I tried to use multer but the problem was same.
Busboy has parameters inside busboy.on('field') event
We explicitly have to attach it to req.body before Busboy.on('finish') event like so :
busboy.on('field', (fieldName, value) => {
req.body[fieldName] = value
})
This will attach parameters to req.body as it should be !

TypeError: "Object is not a function" when using a constructor

I am making a user registration form witch insert a record to the mongodb. I am using there fore:
MongoDB version v2.6.11
NodeJS version v0.10.25
Express version 4.13.1
All works fine except when a use a constructor var newUser = new User({...}); it returns the error Object is not a function
The rest works fine. I get the logging before it returns the error but i don't know how to fix this.
users.js
var express = require('express');
var router = express.Router();
var User = require('../models/user');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/Registreren', function(req, res, next) {
res.render('Registration', { title: 'Registreren' });
});
router.get('/Aanmelden', function(req, res, next) {
res.render('Aanmelden', { title: 'Aanmelden' });
});
router.post('/Registreren', function(req, res, next){
// Get form value
console.log('Bericht in behandeling ...')
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password_confirm = req.body.password_confirm;
console.log('username: ' + username);
console.log('email: ' + email);
console.log('password: ' + password);
console.log('password_confirm: ' + password_confirm);
console.log('FIRST TEST: ' + JSON.stringify(req.file));
console.log('SECOND TEST: ' + req.file.profileimage);
console.log('THIRD TEST: ' + req.file.originalname);
// Check for image field
if (req.file || req.file.profileImage){
console.log('Uploading file....');
//File Info
var profileImageOrginalName = req.file.originalname;
var profileImageName = req.file.name;
var profileImageMimetype = req.file.mimetype;
var profileImagePath = req.file.path;
var profileImageExt = req.file.extension;
var profileImageSize = req.file.size;
} else{
console.log('profileImageFile not found....');
// Set default image
var profileImageName = 'noimage.png';
}
// Form validation
req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkBody('email','email is verplicht').notEmpty();
req.checkBody('email','email is niet geldig').isEmail();
req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
req.checkBody('password','Wachtwoord is verplicht').notEmpty();
req.checkBody('password_confirm','Wachtwoorden zijn niet `gelijk').equals(req.body.password);`
// Error handling
var errors = req.validationErrors();
console.log(errors);
if(errors){
console.log('Error handling....');
res.render('Registration',{
errors: errors,
email: email,
username: username,
password: password,
password_confirm: password_confirm
});
} else {
console.log('Make new User ....');
console.log('email: ' + email);
console.log('username: ' + username);
console.log('password: ' + password);
console.log('profileImageName: ' + profileImageOrginalName);
var newUser = new User({
email: email,
username: username,
password: password,
profileimage: profileImageOrginalName
});
console.log('---------------- START TEST----------------------------');
console.log('FIRST TEST: ' + JSON.stringify(newUser));
console.log('SECOND TEST: ' + newUser);
// Create User
User.createUser(newUser, function(err,user){
if(err) throw err;
});
// Succes message
req.flash('succes','Je bent succesvol aangemedld');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
APP.JS
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 session = require('express-session');
var methodOverride = require('method-override');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var flash = require('connect-flash');
var expressValidator = require('express-validator');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle file Uploads
app.use(multer({dest:'./uploads/'}).single('profileimage'));
// 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 }));
//Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Vallidator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Flash
app.use(flash());
app.use('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
user.js
console.log('Mongoose Start....');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Users');
var db = mongoose.connection;
db.once('open', function (callback) {
//user Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
},
email: {
type: String,
},
profileimage: {
type: String,
}
});
console.log('Create record!');
var User = module.exports = mongoose.model('User',UserSchema);
module.exports.createUser = function(newUser, callback){
newUser.save(callback);
console.log('USER: ' + newUser)
};
});
What i have tried an read
I have read the following post:
Node.js: object is not a function
node.js express.js object is not a function call_non_function
TypeError: object is not a function Node.js
I have tried to build more logging as you can see in the scripts so i can pin point where the problem come from. But i don know how to fix this. I hope you can help me.

Resources