NodeJS pass Array from MongoDB to EJS file - javascript

i'm trying to make an option tag for every item which is in my Array in MongoDB. I have tried some ways but EJS throws me everytime the same error "gate is not defined"..
Here is my function in my route:
router.post('/neueBuchung_spediteur', (req, res) => {
User.findOne({username: req.user}, function (err, user) {
res.render('neueBuchung_spediteur', {
gate: user.gate
});
});
And this is my EJS function:
<select id="torauswahl" name="torauswahl" style="padding:10px;font-size: large; width: 300px">
<% for (var i = 0; i < gate.length; i++){%>
<option value="<%=gate[i]%>"><%=gate[i]%></option>
<%}%>
</select>
thats my full JS file for understanding the logic:
const express = require('express');
const router = express.Router();
// Load Buchung model
const Buchung = require('../DB/models/Buchung');
const User = require('../DB/models/User');
const Tor = require(('../DB/models/Tor'));
const { ensureAuthenticated } = require('../DB/config/auth');
const passport = require('passport');
//Startseite Breuninger
router.get ('/startseite_breuninger', ensureAuthenticated, (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('startseite_breuninger',{
vorname: req.user.vorname,
buchungen: buchungen || []
});
});
});
//startseite Spedi
router.get ('/startseite_spediteur', ensureAuthenticated, (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('startseite_spediteur',{
buchungen: buchungen || []
});
});
});
//Buhchungsübersicht mitarbeiter
router.get('/buchungsuebersicht', (req, res) => res.render('buchungsuebersicht'));
//Buhchungsübersicht spedi
router.get('/neueBuchung_spediteur', (req, res) => res.render('neueBuchung_spediteur'));
//torauswahl spedi
router.get ('/torauswahl', (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('torauswahl',{
buchungen: buchungen || []
});
});
});
//torverwaltung mitarbeiter
router.get ('/torverwaltung', (req, res) =>{
Tor.find(function (err, tor) {
if (err)
return res.send(err);
res.render('torverwaltung',{
tor: tor || [],
});
});
});
//Update Benutzerdaten Breuni
router.post('/update_detailansicht_breuninger',(req,res) =>{
const username = req.body.username;
const telefon = req.body.telefon;
const email = req.body.email;
User.update({username: username}, telefon);
res.render('detailansicht_breuninger');
});
//insert
//insert
router.post('/neueBuchung_spediteur',ensureAuthenticated,(req, res) => {
const {sendungsstruktur, datepicker, timepicker1, timepicker2, sendungen, EUP, EWP, pakete, bemerkung, teile } = req.body;
var user = req.user;
if (errors.length > 0) {
User.findOne({ username: req.user}, function (err, user) {
console.log(JSON.stringify(req.user));
if (err) { throw err; }
if (user) {
res.render('neueBuchung_spediteur', {
gate: user.gate || []
});
}
});
}
const newBuchung = new Buchung({
sendungsstruktur,
datepicker,
timepicker1,
timepicker2,
sendungen,
EUP,
EWP,
pakete,
bemerkung,
teile
});
newBuchung.save()
.then(buchung =>{
res.send('saved')
})
.catch(err=>console.log(err));
console.log(newBuchung)
});
router.post(
'/login',
passport.authenticate('local', {
failureRedirect: '/login'
}), (req, res) => {
if (req.user.admin == "spediteur") {
res.redirect('/buchungen/startseite_spediteur');
} else {
res.redirect('/buchungen/startseite_breuninger');
}
});
module.exports = router;
Im thankful for any help :)

I think the issue is that req.user is undefined. Can you try logging req.user during your route function?
router.post('/neueBuchung_spediteur', (req, res) => {
User.findOne({username: req.user}, function (err, user) {
console.log(JSON.stringify(req.user))
res.render('neueBuchung_spediteur', {
gate: user.gate
});
});

Related

How do you nest routes in express?

I am new to express and node and I have this situation:
controller:
exports.find_by_IDN_post = (req, res) => {
console.log('init')
accidentDetail.findOne({ idn: req.body.idn }, (err, data) => {
if (err) {
res.status(500).send(err)
}
console.log(data)
res.status(200).send(data)
})
}
exports.find_by_name_post = (req, res) => {
accidentDetail.findOne({$or: [{'firstName': req.body.name}, {'middleName': req.body.name}, {'surname': req.body.name}]}, (err, data) => {
if (err) {
res.status(500).send(err)
}
res.status(200).send(data)
})
}
exports.find_by_date_post = (req, res) => {
accidentDetail.findOne({firstReg: req.body.firstReg}, (err, data) => {
if (err) {
res.status(500).send(err)
}
res.status(200).send(data)
})
}
exports.find_by_accident_type_post = (req,res) => {
accidentDetail.findOne({accidentType: req.body.accidentType}, (err, data) => {
if (err) {
res.status(500).send(err)
}
res.status(200).send(data)
})
}
route:
const express = require('express')
const router = express.Router()
const query_controller = require('../controllers/QueryController')
router.post('/idn', query_controller.find_by_IDN_post)
router.post('/name', query_controller.find_by_name_post)
router.post('/date', query_controller.find_by_date_post)
router.post('/accidentType', query_controller.find_by_accident_type_post)
module.exports = router
app
const queryRouter = require('./routes/query')
app.use('/query', queryRouter)
How do I nest the routes? I want to be able to access the routes like this:
localhost:3001/query/idn
localhost:3001/query/name
...
At the moment, I can't receive the console.log('init') when trying to access localhost:3001/query/idn.

function with variable returns for routes

I have multiple routes which need the same userdata from the database. I have a function to check if the user is loggend in but that function dont return the user variables.
route:
app.get('/template', isAuthenticated, function (req, res) {
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
const db = client.db(dbname);
let collection = db.collection('users');
// find data in db
collection.findOne({ _id: userid }).then(user => {
if (user != null) {
res.render('template', { layout: 'temaplte', csrfToken: req.csrfToken(), username: user.username, avatar: user.picture });
} else {
console.log("No user with this id!")
}
}).catch((err) => { console.log(err);
}).finally(() => { client.close(); });
});
});
Is there a way to get the variables users from the db from a function like isAuthenticated? Do I need to write the findOne-function on every route?
Best way to reuse logic in routes is to refactor that functionality into its own middleware.
function loadUserData(req, res, next) {
MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err, client) => {
if (err) {
return next(err)
};
const db = client.db(dbname);
let collection = db.collection('users');
// find data in db
collection.findOne({
_id: userid
}).then(user => {
if (user != null) {
req.user = user; // augment the request object with user data (check res.locals docs too)
return next(); // pass control to next middleware
} else {
res.end("No user with this id!");
}
}).catch((err) => {
return next(err);
})
.finally(() => {
client.close();
});
});
}
app.get('/template', isAuthenticated, loadUserData, function(req, res) {
const user = req.user; // loadUserData populated req.user;
res.render('template', {
layout: 'temaplte',
csrfToken: req.csrfToken(),
username: user.username,
avatar: user.picture
});
});

How to merge two files API (Node.js)

I am a node.js and MySQL beginner and I just started setting up and trying out some basic code.
I find these two APIs to practice, one is the API for the CRUD database, and the other is the API for judging user login / registration.I tried to merge the APIs of these two files, and the result was a problem. I think the current problem is the configuration file (conf.js).I plan to write a function and then wrap any file and use it again, so that the configuration files may not conflict, but I don’t know how to start.
These are the two API teaching URLs I practiced
http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-mysql-with-example
https://www.footmark.info/programming-language/nodejs/nodejs-restful-webapi-mysql/
index.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var authenticateController = require("./controllers/authenticate-controller");
var registerController = require("./controllers/register-controller");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/api/register", registerController.register);
app.post("/api/authenticate", authenticateController.authenticate);
app.listen(3000);
app.js
var bodyparser = require("body-parser");
var express = require("express");
var conf = require("./conf");
var functions = require("./functions");
var user = require("./routes/user");
var app = express();
req.body
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
//app.use(functions.passwdCrypto);
app.use("/user", user);
app.listen(conf.port, function() {
console.log("app listening on port " + conf.port + "!");
});
authenticate-controller.js
var connection = require('./../conf');
module.exports.authenticate=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) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
if(results.length >0){
if(password==results[0].password){
res.json({
status:true,
message:'successfully authenticated'
})
}else{
res.json({
status:false,
message:"Email and password does not match"
});
}
}
else{
res.json({
status:false,
message:"Email does not exits"
});
}
}
});
}
register-controller.js
var connection = require('../conf');
module.exports.register=function(req,res){
var today = new Date();
var user={
"name":req.body.name,
"email":req.body.email,
"password":req.body.password,
"created_at":today,
"updated_at":today
}
connection.query('INSERT INTO user SET ?',user, function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
res.json({
status:true,
data:results,
message:'user registered sucessfully'
})
}
});
}
user.js(models)
var mysql = require("mysql");
var conf = require("../conf");
var connection = mysql.createConnection(conf.db);
var sql = "";
module.exports = {
items: function(req, callback) {
sql = "SELECT * FROM user";
return connection.query(sql, callback);
},
item: function(req, callback) {
sql = mysql.format("SELECT * FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
add: function(req, callback) {
sql = mysql.format("INSERT INTO user SET ?", req.body);
return connection.query(sql, callback);
},
delete: function(req, callback) {
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
put: function(req, callback) {
connection.beginTransaction(function(err) {
if (err) throw err;
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
connection.query(sql, function(err, results, fields) {
if (results.affectedRows) {
req.body.id = req.params.id;
sql = mysql.format("INSERT INTO user SET ?", req.body);
connection.query(sql, function(err, results, fields) {
if (err) {
connection.rollback(function() {
callback(err, 400);
});
} else {
connection.commit(function(err) {
if (err) callback(err, 400);
callback(err, 200);
});
}
});
} else {
callback(err, 410);
}
});
});
},
patch: function(req, callback) {
sql = mysql.format("UPDATE user SET ? WHERE userId = ?", [req.body, req.params.id]);
return connection.query(sql, callback);
}
};
user.js(routes)
var express = require("express");
var user = require("../models/user");
var router = express.Router();
router
.route("/")
.get(function(req, res) {
user.items(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.post(function(req, res) {
user.add(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
res.status(201).json(results.insertId);
});
});
router
.route("/:id")
.get(function(req, res) {
user.item(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.delete(function(req, res) {
user.delete(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
res.sendStatus(204);
});
})
.put(function(req, res) {
user.put(req, function(err, results) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (results === 410) {
res.sendStatus(410);
return;
}
user.item(req, function(err, results, fields) {
res.json(results);
});
});
})
.patch(function(req, res) {
user.patch(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
req.body.id = req.params.id;
res.json([req.body]);
});
});
module.exports = router;
conf.js
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "farmbot",
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports = connection;
/*If I comment out the code below, I can execute the login / register API*/
/*Without commenting out, can only perform CRUD on the database*/
module.exports = {
db: {
host: "localhost",
user: "root",
password: "1234",
database: "farmbot"
},
port: 3000
};
You will have to refactor them properly. You will need only once file to begin with. Why using it twice?
Refactor them in one file instead of listening to them on different ports. Once done, you can show the code to us so that we can fix it further if there's an issue.
Start from index.js and merge app.js with it but a bit carefully. I think doing it by yourself you will learn much from it.

Data and salt arguments required error (authorization)

I'm a beginner in NodeJS and I've tried to make an authentication form using NodeJS + express. I want to make a validation for my password (when "confirmpassword" is different than "password" it should return nothing. Unfortunately, I keep getting "data and salt arguments required". I tried in different ways, to put some conditions, but I keep getting this error. Any ideas how I should make it work?
Here is the file user.js:
const pool = require('./pool');
const bcrypt = require('bcrypt');
function User() {};
User.prototype = {
find : function(user = null, callback)
{
if(user) {
var field = Number.isInteger(user) ? 'id' : 'username';
}
let sql = `SELECT * FROM users WHERE ${field} = ?`;
pool.query(sql, user, function(err, result) {
if(err)
throw err
if(result.length) {
callback(result[0]);
}else {
callback(null);
}
});
},
create : function(body, callback)
{
var pwd = body.password;
var cpwd = body.confirmpassword;
// here i hash the pass
body.password = bcrypt.hashSync(pwd,10);
body.confirmpassword = bcrypt.hashSync(cpwd, 10);
if (body.password != body.confirmpassword){
callback(null);
}
else {
var bind = [];
for(prop in body){
bind.push(body[prop]);
}
let sql = `INSERT INTO users(username, fullname, password) VALUES (?, ?, ?)`;
pool.query(sql, bind, function(err, result) {
if(err) throw err;
callback(result.insertId);
});
}
},
login : function(username, password, callback)
{
this.find(username, function(user) {
if(user) {
if(bcrypt.compareSync(password, user.password)) {
callback(user);
return;
}
}
callback(null);
});
}
}
module.exports = User;
And the file pages.js:
const express = require('express');
const User = require('../core/user');
const router = express.Router();
const user = new User();
router.get('/', (req, res, next) => {
let user = req.session.user;
if(user) {
res.redirect('/home');
return;
}
res.render('index', {title:"My application"});
})
router.get('/home', (req, res, next) => {
let user = req.session.user;
if(user) {
res.render('home', {opp:req.session.opp, name:user.fullname});
return;
}
res.redirect('/');
});
router.post('/login', (req, res, next) => {
user.login(req.body.username, req.body.password, function(result) {
if(result) {
req.session.user = result;
req.session.opp = 1;
res.redirect('/home');
}else {
res.send('Username/Password incorrect!');
}
})
});
router.post('/register', (req, res, next) => {
let userInput = {
username: req.body.username,
fullname: req.body.fullname,
password: req.body.password
};
user.create(userInput, function(lastId) {
if(lastId) {
user.find(lastId, function(result) {
req.session.user = result;
req.session.opp = 1;
res.redirect('/home');
});
}else {
console.log('Error creating a new user ...');
}
});
});
router.get('/logout', (req, res, next) => {
if(req.session.user) {
req.session.destroy(function() {
res.redirect('/');
});
}
});
module.exports = router;
In userInput, you are not passing confirmpassword property.
let userInput = {
username: req.body.username,
fullname: req.body.fullname,
password: req.body.password
};
In create method, you are accessing it.
var cpwd = body.confirmpassword;
cpwd is null, and that's the reason for the error.
body.confirmpassword = bcrypt.hashSync(cpwd, 10);//**cpwd is null**
As per the docs, data is required argument and this cannot be null.
hashSync(data, salt)
data - [REQUIRED] - the data to be encrypted.
salt - [REQUIRED] - the salt to be used to hash the password.

Node.js Error: Route.get() requires callback functions but got a [object Undefined]

Hello i know that this question is common in stackoverflow but i passed by all of them and i really cannot get what is wrong with my code.
This is my main server.js
var dbUri = process.env.MONGODB_URI;
var app = express();
var PORT = process.env.PORT || 3001;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
if (app.settings.env === 'development') {
dbUri = 'mongodb://localhost/barsDb';
}
mongoose.connect(dbUri, function (err, res) {
if (err) {
console.log('Erorr connection to database ' + dbUri + '.' + err);
} else {
console.log('Connected to database on ' + dbUri + "\n");
}
});
//app.use(require('./routes.bars'));
require('./routes.bars')(app); //error here reciving undefined
// connect to server
app.listen(PORT, function () {
console.log('Listening to port ' + PORT + '...');
});
These are my routes.js
var bars = require('./controllers/controller.bar');
var mongoose = require('mongoose');
module.exports = function(app) {
app.route('/').get(bars.getMain); //error in this line it is returning undefinded.
app.route('/bars').get(bars.getBars);
app.route('/bars').post(bars.addBar);
app.route('/bars/:id').put(bars.updateBarById);
app.route('/bars/:loc').get(bars.getByLocation);
app.route('/bars/:id').get(bars.getBarById);
app.route('/bars/:id').delete(bars.deletBarById);
};
This is my controller:
var mongoose = require('mongoose');
var dbModel = require('./../model/bars.db');
var path = require('path');
var _ = require('underscore');
// main page
module.getMain = function (req, res) {
res.sendFile(path.join(__dirname + "/../public/index.html"));
};
// post new bar
module.addBar = function (req, res) {
var body = _.pick(req.body,'name', 'address', 'phone', 'barType', 'ambient', 'options', 'loc');
console.log(body);
var newBar = new dbModel(body);
newBar.save(function (err) {
if (err) throw err;
//res.send('Bar Created');
res.status(201).send();
});
};
// get all bars
module.getBars = function (req, res) {
dbModel.find({},function (err, bars) {
if (err) throw err;
res.json(bars);
//res.status(200).send();
});
};
//get bars by location
module.getByLocation = function (req, res) {
var barLoc = req.params.loc.split(",");
var barLocLon = parseFloat(barLoc[0]);//.toFixed(5);
var barLocLat = parseFloat(barLoc[1]);//.toFixed(5);
barLoc = []; barLoc.push(barLocLon); barLoc.push(barLocLat);
dbModel.find({
loc: {$gt:[barLocLon - 0.0200, barLocLat - 0.0200], $lt:[barLocLon + 0.0200, barLocLat + 0.0200]}
}, function (err, bars) {
if (err) throw err;
res.json(bars);
res.status(200).send();
});
};
// get bar by id:
module.getBarbyId = function (req, res) {
var barId = req.params.id;
dbModel.findById(barId, function (err, bar) {
if (err) throw err;
res.json(bar);
res.status(200).send();
});
};
// update bar by id:
module.updateBarById = function (req, res) {
var barId = req.params.id;
var body = _.pick(req.body,'name', 'address', 'phone', 'barType', 'ambient', 'options', 'loc');
dbModel.findById(barId, function (err, bar) {
if (bar) {
bar.save(function (err) {
if (err) throw err;
});
}
});
dbModel.findByIdAndUpdate(barId, {$set:req.body}, function (err, bar) {
if (err) throw err;
res.send('Updated');
});
};
// delete bar by id:
module.deleteBarById = function (req, res) {
var barId = req.params.id;
//console.log(barId);
dbModel.findByIdAndRemove(barId, function (err) {
if (err) throw err;
res.send('Deleted id ' + barId);
});
};
Wrap your functions like this.
var myFunctions = {
// get bar by id:
getBarbyId: function (req, res) {
var barId = req.params.id;
dbModel.findById(barId, function (err, bar) {
if (err) throw err;
res.json(bar);
res.status(200).send();
});
},
// update bar by id:
updateBarById: function (req, res) {
var barId = req.params.id;
var body = _.pick(req.body, 'name', 'address', 'phone', 'barType', 'ambient', 'options', 'loc');
dbModel.findById(barId, function (err, bar) {
if (bar) {
bar.save(function (err) {
if (err) throw err;
});
}
});
dbModel.findByIdAndUpdate(barId, {
$set: req.body
}, function (err, bar) {
if (err) throw err;
res.send('Updated');
});
},
// delete bar by id:
deleteBarById: function (req, res) {
var barId = req.params.id;
//console.log(barId);
dbModel.findByIdAndRemove(barId, function (err) {
if (err) throw err;
res.send('Deleted id ' + barId);
});
}
}
module.exports = myFunctions;
Now you can you use your "controller" like this:
var myControllerFuncs = require('path/controller.js');
//myControllerFuncs.updateBarById...

Categories