Express routes passing data to view - node.js

I have data that I am able to log to the console but can't figure out how to make it available to my view.
The following works to console.log req.user upon signing in to an admin page
app.use(function(req, res, next){
console.log(req.user);
next();
});
The entire JSON object is passed into the console. I'd like to be able to pass it into my view but can't seem to make the following logic work. I'm either not passing it into the route correctly or not pulling it out into ejs correctly.
app.get('/', function(req, res) {
res.render('index.ejs',{
bootstrappedUser: req.user
});
});

What version of express are you using?, I dont see error in your code , but maybe in config files.Are you setting app.set('view engine','ejs')?,maybe your index.ejs file is not in the correct folder so you need to move it to /views in the root folder of your application.

Related

router.param not triggering passport.js initialize in app.use

I've got a fairly straight forward Node Express routing app set up, to which I've just added passport.js authentication. I'm now trying to integrate this with the existing routes.
I run the basic middleware of:
app.use(passport.initialize());
app.use(passport.session());
and then if I run a simple
app.get('/route', (req, res)=>{
console.log(req.user)
});
I get the expected result of it printing the logged in user. So far so good...
However, I'm now trying to access this req.user within some of the child routes that I have set up. In the first route I'm trying the first step is to bring in a parameter and compare it against the req.user:
app.use('/route/:userId', idRouter);
And then:
idRouter.param("userId", async (req, res, next, userId) => {
console.log(userId)
console.log(req.user.id)
})
This route fires and prints out the parameter, but req.user is undefined. I can't see a reason why this is the case.
To help debug this I've put some logging in the deserialize function and I can see that it's not being called when I hit the idRouter. I can't see why this would be the case given it's inside an app.use function which should be called every time.
Help please!
I solved this in the end, it was an issue with CORS. Just needed to include credentials in API calls.

Node React structure without view engine

I'm new to node. I was using express-handlebars as my view-engine, but now I've added React and I understood that I no longer require handlebars. The problem that I'm having is that in order to get to the index.html page, without handlebars, I had to use
app.use(express.static('./public'));
Everything gets rendered from react, but what if I want to do some other things when the user goes to the index page like
app.get("/",function(req,res){
console.log("connected");
});
If I add the get request after exporting the static files, the console.log never gets called. If I use it before, it does get called, but I can see the page loading forever. How should I structure the application now that I'm using react and I don t have a view engine anymore?
In your specific case, if you don't want to render anything to the user, you should turn your function into a middleware :
app.get("/",function(req,res, next){
console.log("connected");
next();
});
and put it before the app.use(express.static('./public'));
However, if you want to do actual logic with return values and such, I would suggest that you setup some kind of API that you request using Ajax from the client.
You can check my repository
https://github.com/kennethmervin01/react-node-production
it's a boilerplate to serve react app in node.js/express
then check my code inside app.js
You just need to copy the production build of your react app inside the react folder
app.use(express.static(path.join(__dirname, "../react")));
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "../react", "index.html"));
});

allow access to html page only to logged in users

I have app.html in a public folder which is serving static files to express.
I have used code from here.
But instead of profile.ejs from views folder(as per the code in link), I want to serve app.html from inside of public folder.
app.get('/app.html', isLoggedIn, function(req, res) {
res.render('app.html'/*, {
user : req.user // get the user out of session and pass to template
}*/);
console.log("APP.HTML");
});
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
But it does not restrict the access to loggedIn users and I am able to access it directly after logging out as well.
What could be wrong here?
The problem is most likely that you have express.static() before your app.get() line. The static middleware checks if the file exists and sends it if it does. So you need to put that app.get() before your express.static() middleware.

nodejs express static routes creating multiple sessions

I am using Nodejs and Express. I have a routes.js file defining all my routes. When I try to use req.session.regenerate(), express creates multiple sessions including one each for static file requests as well.
Whats confusing is req.session.regenerate() is within app.get('/' route and it seems from the console.log it gets called only once. But somehow when I look at the mongodb session collection, there are multiple sessions created for one page request.
basically what I am trying to do is when the login page is requested I want to create a new session so that express does not re-use previous session's cookie.
Any pointers?
routes.js
exports = module.exports = function(app, passport) {
//When I uncomment this line, it shows me the number of times a request is made.
//app.all('*', function(req, res, next){console.log('Request made to server'); next();});
app.get('/', function(req, res){
if (req.isAuthenticated()){
res.redirect('./home');
}else{
req.session.regenerate(function(err) {
console.log('Regenerated');
})
res.render('./login')
}
});
Put your express session middleware after your express.static() middleware.

Using session variables in jade template in node js

is there any alternate for using session variables in jade template file other than using dynamic helper function and passing it through res.render?
if i use dynamichelpers method its showing error since it is deprecated. please help
app.use(function(req, res, next){
res.locals.user = "xxxx";
next();
});
i used this code in app.js inside app.configure function. but still i couldn't use the variable user in my view. do i need to install any additional packages or any other code?
This code should work. For example, I'm using nearly identical code in one of my production systems:
app.use(function (req, res, next) {
app.locals.token = req.session._csrf;
app.locals.user = req.user;
...
next();
});
You'll need to make sure this code is after you set req.locals.user - for example, if you are using Passport, after you do the initialize and session code, but before you actually handle and render the request.

Resources