Using session variables in jade template in node js - 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.

Related

What does res.locals.path = req.path; in node.js?

I try to figure out what this code does:
const app = express();
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
res.locals is typically used to surface variables from middleware to a template engine being used to render the page with res.render() in a subsequent request handler (later in the request handler chain). You can read the doc here.
So, this particular middleware is making req.path available to the template engine (by putting that value into res.locals.path so that it can be used in rendering the page as just path (not sure what the template wants to do with the path - that's up to it).
Note that the actual route that is calling res.render() can pass data directly to the template engine as an argument to res.render(), but this can't be done by middleware because the middleware itself isn't calling res.render(), so its alternative is to put the data into res.locals where the template engine can pick it up from there.
res.locals starts out each request as empty so it contains nothing until your middleware or request handlers puts something in it for purposes of rendering a page for that specific request.

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.js cannot view headers inside middleware

I have a Node.js restful API. The problem I am having is that I am not sure why I am not able to see the request headers inside the middleware route.use(), however, it is visible inside get method router.get('/',function(req,res){}).
Can you someone please why is this case or what do I have to do get it visible inside
router.use(function(req,res,next){ next();});
Try something like his
router.use(function (req, res, next) {
console.log(req.headers['header_name']);
if (!req.headers['header_name']) return next('router')
next()
})
To skip the rest of the router’s middleware functions, call next('router') to pass control back out of the router instance.

Node dynamic routing when route is undefined

I am new with node and am trying to figure out dynamic routing. I have routes already set up such as
app.route('/users')
.get(dbController.collect)
.post(dbController.insert);
app.route('/users/:userId')
.get(dbController.read)
.put(dbController.update)
.delete(dbController.delete);
I want to be able to do something similar for routes that I have not defined in my code while still letting the routes I have defined work as usual. For example if someone was to send a get request to https://example.com/books/12 it would dynamically run the read function as it does for users.
Express routing allows you to do catch-all routes:
app.all('*', (req, res) => {
console.log('Route is unknown')
// Do something here...
})

Express routes passing data to view

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.

Resources