Undefinded error - node.js

route.js
router.get('/restful', function(req, res){
console.log("before");
User.show_deatils(req, res, function(err, resultArray){
if(!err) {
req.session.resultArray=resultArray;
}
});
console.log(req.session.resultArray);
res.render('restful',{resultArray:req.session.resultArray});
});
I don't know why I am getting as undefined when I am doing it console.log() in the above position.If I do console.log() just after the req.session.resultArray=resultArray then we are getting the result array.
I want to display this resultArray in my view.ejs. Can anyone suggest me how to solve it.What is the thing I am missing it out?

The console.log runs before the async function actually gets the details from the database. so you get undefined.
Do the render inside the callback. i.e, after you assign result array to session.
router.get('/restful', (req, res, next) {
User.show_deatils(req, res, function(err, resultArray) {
if(!err) {
req.session.resultArray=resultArray;
return res.render('restful' {resultArray:req.session.resultArray}));
}
});
});

Just do like this
router.get('/restful', function(req, res){
console.log("before");
User.show_deatils(req, res, function(err, resultArray){
if(!err) {
res.render('restful',{resultArray:resultArray});
}
});
});
I think this is what you want.

Related

why am i getting this error when i try to req.logout()?

Error which i am getting:
Error: req#logout requires a callback function
My code:
// #desc Logout User
// #rote GET /auth/logout
router.get("/logout", (req, res)=>{
req.logout()
res.redirect("/")
})
req.logout() is an asynchronous function (it was not this way before, they only introduced this change recently for security reasons), and your current code is synchronous, which is why you get this error.
You can fix this error by modofying your code as follows:
app.post('/logout', function(req, res, next) {
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
This is a change introduced in recent release. You can find it here in detail https://medium.com/passportjs/fixing-session-fixation-b2b68619c51d
From the documentation https://www.passportjs.org/concepts/authentication/logout/
try below code
router.get("/logout", function(req, res, next) {
req.logout(function(err) {
if (err) {
return next(err);
}
res.redirect("/");
});
});

Why is req.IsAuthenticated() return false even that req.session.passport.user has everything

Hi I have the following code. After I did req.login, req._passport has the right information there. However, after I call res.redirect("/profile"), inside my isAuthenticated function, req._passport is undefined, but req.session.passport.user has the right information. I looked at the req.isAuthentication method, it was looking for req._passport. Any reason why req._passport is undefined after redirect, and why there are both req._passport and req.session.passport? Thanks!
app.post('/signin', function (req, res, next) {
passport.authenticate('local-signin', function (err, user, info) {
......
req.login(user, function (err) {
console.log(req._passport); // Here req._passport is set.
return res.redirect('/profile');
});
});
})(req, res, next);
});
app.get('/profile', isAuthenticated, profile.index);
function isAuthenticated(req, res, next) {
console.log(req.session.passport.user); // looks good
console.log(req._passport) // undefined
if (req.isAuthenticated()) {
console.log("authenticated"); // Not reaching here
return next();
}
console.log("not authenticated"); // reaching here
res.redirect('/signin');
}

req.params.id is undefined, I can't figure out why

Here is the url in browser:
http://localhost:3001/user/59cc018171149931f4e435ac
This is the code for the route:
router.get("/new", middleware.userLoggedIn, function(req, res){
console.log(req.params.id);
//find user by id
User.findById(req.user._id, function(err, foundUser){
if(err) {
console.log(err);
} else {
res.render("characters/addCharacter", {user: foundUser});
}
});
});
This is the middleware:
middlewareObj.userLoggedIn = function(req, res, next) {
// eval(require('locus'));
if (req.isAuthenticated() && req.params.id.equals(req.user._id)) {
return next();
}
res.redirect("/login");
};`
When I run the app everything works fine. Expect the request on the route above, wich giving me the error "TypeError: Cannot read property 'equals' of undefined". When I take off the middleware and try to console.log(req.params.id), it returns "undefined". What am I doing wrong?
Edit:
I have my route configured in app.js:
app.use("/user/:id/characters", characterRoutes);
So the ":id" is there.
When i use /new/:id instead of /new geting new error message:
"Cannot GET /user/59c23b864262fc2c186677be/characters/new"
use /new/:id instead of /new
router.get("/new/:id", middleware.userLoggedIn, function(req, res){
console.log(req.params.id);
//find user by id
User.findById(req.user._id, function(err, foundUser){
if(err) {
console.log(err);
} else {
res.render("characters/addCharacter", {user: foundUser});
}
});
});
You have to specify the parameter you want in your path, like so /new/:id and then you can use req.params.id in your code.
Here's the Express documentation for this part
cast req.params into any first:
let params: any = req.params
and then params.id should work

Display of data on view from route.js

// This is my router.js
router.get('/restful', function(req, res){
console.log("before");
User.show_deatils(req, res, function(err, resultArray){
if(!err){
req.session.resultArray=resultArray;
req.session.save();
}
});
//console.log(req.session.resultArray)
res.render('restful',{resultArray:req.session.resultArray});
});
//This is model.js
module.exports.show_deatils=function(req,res,callback){
var resultArray=[];
mongo.connect(url,function(err,db){
assert.equal(null,err);
var cursor=db.collection('users').find();
cursor.forEach(function(doc,err){
assert.equal(null,err);
resultArray.push(doc);
callback(null, resultArray);
});
});
}
//I want to display the resultArray on loading view(restful.ejs).But the problem is when I first redirect to the page.It is not showing any value.But upon clicking the same page its been showing me the details.What I feel is on the first load it is not storing the values in session.How can we solve this issue?I am trying this for long time.
That is because you are rendering outside the async callback function
Change your code like this
router.get('/restful', function(req, res){
console.log("before");
User.show_deatils(req, res, function(err, resultArray){
if(!err){
req.session.resultArray=resultArray;
req.session.save();
res.render('restful',{resultArray:req.session.resultArray});
}
});
//console.log(req.session.resultArray)
});
It is storing correct in the session, that part is working but since the first time you are rendering outside the async callback, it has no value.

NodeJS extra field with byId();

Currently I am working on a nodeJS API, I have a model, and that model can have Media items, as you can see in my code here:
router.get('/:id', function(req, res, next) {
qbuilder.byId(Model,req)
.exec(
function(err,model){
Media.count({'model.entity': model._id}, function(err, media){
if(media){
console.log(media);
}
});
model.total_media = 15;
responders.sendJsonOrError(err, res, model, next);
});
});
Problem is, that the code:
model.total_media = 15;
Is not showing up in the responder, which is strange, because if I clean the object with: model = []; it returns empty.
Once I add lean() to my query, it returns the total_media in the responder, but then I get the problem that when I do like this:
router.get('/:id', function(req, res, next) {
qbuilder.byId(Model,req)
.exec(
function(err,model){
Media.count({'model.entity': model._id}, function(err, media){
if(media){
model.total_media = media;
}
});
responders.sendJsonOrError(err, res, model, next);
});
});
It is not populating the total_media, is there any other way to do this correctly?
Try with this. The response is sending before you assign values.
router.get('/:id', function(req, res, next) {
qbuilder.byId(Model,req)
.lean().exec(
function(err,model){
Media.count({'model.entity': model._id}, function(err, media){
if(media){
model.total_media = media;
}
responders.sendJsonOrError(err, res, model, next);
});
});
});

Resources