dynamic url using express.js confusion - javascript

router.get('/:username', function(req, res, next) {
res.render('dashboard');
});
router.get('/', function(req, res, next) {
if(req.user) // this has value
res.redirect('/'+req.user);
});
If user logged in, he will redirect to example.com/his_name, but I got example.com/undefined. When I do console.log(req.user), it has value. Why?

Try storing req.user in a variable like this:
router.get('/', function(req, res, next) {
var currentUser = req.user;
if(currentUser) // this has value
res.redirect('/'+currentUser);
});

Related

express next throwing error as next is not defined

I am trying to pass some predefined functions in the callback of app.post() method. I am getting next is not defined error. Below is my code. Please suggest where I am doing wrong or am I missing any concept here?
var express = require('express');
var app = express()
app.post('/api/signup', function(req, res) {
validateParams(req, res, next),
dbCall(req, res, next),
sendResponse(req, res)
})
where I have each function defined and imported and returning next() after my process.
my validateParams function is below :
validateParams = function(req, res, next) {
console.log("at validator ", req);
next();
}
module.exports = validateParams;
my dbCall function is below :
dbCall = function(req, res, next) {
console.log("at dbCall ", req);
next();
}
module.exports = dbCall;
my sendResponse function is below :
sendResponse = function(req, res) {
console.log("at dbCall ", res);
res.send("Response sent successfully");
}
module.exports = sendResponse;
You probably forgot to add the next argument in your callback.
app.post('/api/signup', function(req, res, next) {
validateParams(req, res, next),
dbCall(req, res, next),
sendResponse(req, res)
})
I think you are trying to use validateParams(req, res, next) and dbCall(req, res, next) as middleware functions. In this case, you need something like this:
const validateParams = (req, res, next) => {
// do stuff here
next();
}
const dbCall = (req, res, next) => {
// do stuff here
next();
}
app.post('/api/signup', validateParams, dbCall, function(req, res) {
sendResponse(req, res)
})
You can read more here

Can't set headers after they are sent error

In my app.js I do this
app.use(function(req, res, next){
if(!req.user){
return res.redirect('/login_');
}
next();
})
I don't see anything wrong and in route/index.js I do
router.get('/login_', function(req, res) {
res.render('login', { user : req.user });
});
But I got an error. I know this is caused by the request is not ended but what's wrong with my code above? clueless with this error.
Full code of route/index.js
var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads')
}
})
var upload = multer({ storage: storage })
var Photo = require('../models/photos');
router.get('/', function(req, res, next) {
if(req.user){
res.redirect('/'+req.user.username+'/screen');
}else{
res.redirect('/login_');
}
});
router.get('/:username/screen', function(req, res, next) {
res.render('screen', { user : req.user });
});
router.get('/:username', function(req, res, next) {
var excludes = ["/login_", "/register_","/logout_"];
if (excludes.indexOf(req.originalUrl) > -1){
return next();
}else{
res.render('upload_photo');
}
});
router.post('/:username', upload.any(), function(req, res, next) {
var excludes = ["/login_", "/register_","/logout_"];
if (excludes.indexOf(req.originalUrl) > -1){
return next();
}else{
var photo = new Photo({
photo:req.files[0].filename,
caption:req.body.caption
});
photo.save(photo);
res.sendStatus(200);
}
});
router.get('/:username/manager', function(req, res, next) {
Photo.getAllPhotos(function(err,result){
var headers = req.headers.host;
var pathname = '128.199.128.108:3000';
if(headers.indexOf('localhost') > -1){
pathname = 'localhost:3000'
}
res.render('manager',{pathname:pathname,photos:result});
});
});
//* passport for register/login_ *//
router.get('/register_', function(req, res) {
res.render('register', { });
});
router.post('/register_', function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});
router.get('/login_', function(req, res) {
res.render('login', { user : req.user });
});
router.post('/login_', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
router.get('/logout_', function(req, res) {
req.logout();
res.redirect('/login_');
});
module.exports = router;
You are printing something before this line.
Either trace that, or instruct your server to cache some of the output to the user.
(if the server does not display anything to the user, headers can be sent, even if code tries to print something before)
However that is general knowledge, not familiar with node.js

When refresh browser then error come "can't set headers after they are sent"

Error image:
app.get('/home', function (req, res, next) {
usersession = req.session;
if (usersession.loggedin == true)
res.redirect('/home');
res.sendFile(path.join(__dirname, 'index.html'));
});
When home page refresh then error comes
The if doesnt stop res.sendFile from executing after you have redirected.
app.get('/home', function (req, res, next) {
usersession = req.session;
if (usersession.loggedin) {
return res.redirect('/home');
}
res.sendFile(path.join(__dirname, 'index.html'));
});
Note: You should be ideally using router instead of app.

NodeJs routing middleware error

I am trying to implement a middleware that will check if a user is authenticated before the server delivers a page. Although it looks like the process of doing this is simple, node is throwing an error which says "Can't set headers after they are sent".
My router's code is:
module.exports = function(app) {
app.get('/', checkAuth, require('./myAuthenticatedPage').get);
app.get('/login', require('./myLoginPage').get);
};
The myAuthenticatedPage.js:
exports.get = function(req, res) {
res.render('index');
};
The myLoginPage.js:
exports.get = function(req, res) {
res.render('login');
};
The checkAuth.js:
module.exports = function (req, res, next) {
if(!req.session.user) {
res.redirect('/login');
}
next();
}
Any help on this will be greatly appreciated.
Thanks
If you aren't authenticated, you'll redirect the user and then try to render the index page. This causes the http headers to be sent twice, hence the error "Can't set headers after they are sent".
In checkAuth.js try:
module.exports = function (req, res, next) {
if(!req.session.user) {
res.redirect('/login');
} else {
next();
}
}

Expressjs routes with username

Im trying to use the username as route in expressjs, to view their profile.
app.get('/:username', function (req, res, next) {
users.get_user(req.params.username, function (err, results) {
if(results[0]) {
res.render('/profile', {
title: 'Profile',
userinfo: results[0]
});
} else {
next();
}
});
});
users.get_user is a function wich gets the user from the db. If it doesn't find a user it goes on to the next route. I also have a lot of other pages like /start, /forum etc. Is this an insufficient way of doing this, because theres a call to the db each time it passes through the /:username route. My question is, is there a better more sufficient way?
Try defining the more specific routes (e.g. /start, /forum) before the /:username route in your application. Express matches routes in the order that you define them.
E.g. Do this:
app.get('/start', function(req, res, next) {...});
app.get('/forum', function(req, res, next) {...});
app.get('/:username', function(req, res, next) {...});
Not
app.get('/:username', function(req, res, next) {...});
app.get('/start', function(req, res, next) {...});
app.get('/forum', function(req, res, next) {...});
This way, if the user goes to /start, it won't hit the /:username route and cause a database hit.

Categories

Resources