Expressjs routes with username - javascript

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.

Related

Express js 4x :req.params returns empty object

Trying to get URl parameters in express js,but got empty object.
var password= require('./routes/password');
app.use('/reset/:token',password);
password.js
router.get('/', function(req, res, next) {
console.log(req.params);
res.send(req.params);
});
console.log(req.params) output is {}
Access url :http://localhost:3000/reset/CiVv6U9HUPlES3i0eUsNwK9zb7xVZpfHsQNuzMNWqLlGA4NJKoagwbcyiUZ8
By default, nested routers do not get passed any parameters that are used in mountpaths from their parent routers.
In your case, app is the parent router, which uses /reset/:token as a mountpath, and router is the nested router.
If you want router to be able to access req.params.token, create it as follows:
let router = express.Router({ mergeParams : true });
Documented here.
You are getting params and query mixed up.
Query approach
Your code should look like this when using query values for the example url: www.example.com?token=123&foo=bar
router.get('/', function(req, res, next) {
console.log(req.query);
console.log(req.query.token); // to log value of token
console.log(req.query.foo); // to log value of foo
res.send(req.query);
});
Params approach
Your code should look like this when using params values for the example url: www.example.com/123
router.get('/:token', function(req, res, next) {
console.log(req.params);
console.log(req.params.token); // to log value of token
res.send(req.params);
});
Instead you can use a middleware to log the path params:
const logger = (req, res, next)=>{
console.log(req.params)
res.send(req.params)
next()//<----very important to call it.
};
app.use(logger); //<----use to apply in the app
router.get('/', (req, res, next)=>res.send('Logged.'));
Actually you messed it up a little bit. You have to pass instance of express to your module.
Server.js:
//adding modules
require('./routes/password')(app);
Password.js:
module.exports = function(router) {
router.get('/reset/:token', function(req, res, next) {
console.log(req.params);
res.send(req.params);
});
//and so on.. your routes go here
}

dynamic url using express.js confusion

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);
});

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();
}
}

Sails data from service to controller

I'm starting with sails js and node more generally .
I'm trying to use the regular way of implementing services in sails to pass data in my controller.
for example, I've a dashboard view, called dashboard.ejs
my view is correctly routed and everything.
But the regular ways of passing data from service wasn't working at all, and I ended up with that to make it work, which seems to be very unappropriate:
my CountService.js:
module.exports = {
RoomCount: function(req, res, cb, tab)
{
Room.count().exec(function(err, roomfound){
tab.push(roomfound);
cb(req, res, tab);
});
},
VenteCount: function(req, res, cb, tab)
{
Vente.count().exec(function(err, ventefound){
tab.push(ventefound);
cb(req, res, tab);
});
},
LotCount: function(req, res, cb, tab)
{
Lot.count().exec(function(err, lotfound){
tab.push(lotfound);
cb(req, res, tab);
});
}
};
My DashboardController.js
module.exports = {
dashboard: function(req, res, next)
{
var tab = []
var end_dashboard = function(req, res, tab){
res.view('dashboard', {
roomCount: tab[0],
venteCount: tab[1],
lotCount: tab[2]
});
};
var callbacklot = function(req, res, tab){
end_dashboard(req, res, tab);
};
var callbackvente = function(req, res, tab){
CountService.LotCount(req, res, callbacklot, tab);
};
var callbackroom = function(req, res, tab){
CountService.VenteCount(req, res, callbackvente, tab);
};
CountService.RoomCount(req, res, callbackroom, tab);
},
};
And then I can call the VenteCount etc values in my view ejs
The regular way was giving a value = undefined
I think I was wrong in the res() or next() part so I ended like that but it makes the service thing very complicated...
Thanks a lot for your help

Express 4 router.route: route not found

I'm running into a strange issue. The first route is working, but the parameterized route returns a 404 error.
var express = require('express');
var router = express.Router();
router.route('/')
.get(function (req, res, next) {
res.send('A list of vehicles.');
})
.post(function (req, res, next) {
res.send('You added a vehicle!');
});
router.route('/:id')
.get(function (req, res, next, id) {
res.send('Vehicle: ' + id);
})
.put(function (req, res, next, id) {
res.send('You edited vehicle: ' + id);
});
If I add this route:
router.route('/test')
.get(function (req, res, next) {
res.send('This is a test.');
});
...I can hit that endpoint. This also seems to work with another router I'm using, which is using router.get(path, function) and router.post(path, function) instead of the router.route(path).get()... methodology.
Am I missing something obvious here? I'm using Express ~4.12.
Gah, I'm an idiot. Just figured this out. I saw an example that used this function signature:
.get(function (req, res, next, id) {
res.send('Vehicle: ' + id);
})
This apparently doesn't work. I'm not sure if the http methods check the arity of the function, but this did work:
.get(function (req, res, next) {
res.send('Vehicle: ' + req.params.id);
})
I don't remember where I saw that example, but hopefully this helps someone.

Categories

Resources