Express: Render partially in each handler? - express

I have a modest little site that uses Express and Pug. Every page has a navbar that contains the user's name drawn from a user parameter and the main content of the page is below which uses a data parameter. The main content is rendered from a template that extends the root template. Both need their own parameter to render properly.
Is there a way to partially render a view in each handler?
var app = require('express')()
app.set('view engine', 'pug')
app.get('/', (req, res, next) => {
var userdata = '...'
req.render('/index', {user: userdata}
next() // the request is for /page
})
app.get('/page', (req, res, next) => {
var moredata = '...'
req.render('./page/index', {data: mroedata})
})

AFAIK that's not possible, but as an alternative, you can use res.locals to achieve something similar:
let userMiddleware = (req, res, next) => {
let userdata = '...';
res.locals.user = userdata;
next();
});
app.use(userMiddleware);
// This can stay the same:
app.get('/page', (req, res, next) => {
var moredata = '...'
req.render('./page/index', {data: mroedata})
})
This is a middleware that will make the user variable available to all of your templates, which seems to me is what you want.
Instead of applying it globally, you can also use it for specific routes:
app.get('/page', userMiddleware, (req, res) => ...);

Related

node axios as middleware

I am trying to construct a middleware and then use it within the app.get route.
I know it's looks very "pioneer" but i am learning.... How can io get it to work?
const BooksMiddle = async (req, res, next) => {
axios
.get(`https://www.googleapis.com/books/v1/volumes/? q=${term}&keyes&key=${process.env.GBOOKSKEY}`)
.then((result) => {
const data = result.data;
const books = data.items;
return books;
});
next();
}
module.exports = textMiddle;
app.get("/", textMiddle, (req, res, next) => {
res.render('index');
});
If the point of this middleware is to get some book data and make that available for your template rendering, then you can put that data into res.locals where templates called from res.render() will automatically look for data:
const bookMiddle = async (req, res, next) => {
axios
.get(`https://www.googleapis.com/books/v1/volumes/?q=${term}&keyes&key=${process.env.GBOOKSKEY}`)
.then((result) => {
res.locals.books = result.data.items;
next();
}).catch(next);
}
module.exports = bookMiddle;
And, then after you import bookMiddle, you can use it like this:
app.get("/", bookMiddle, (req, res, next) => {
res.render('index');
});
If you refer to the books data structure in your template, the template engine will look in res.locals.books for that data (where the middleware puts the data).

How can I route all calls starting with string api to their handlers in an express middleware

I have a express app.js with typical
app.get('/path1', (req, res => {})
app.get('/path2', (req, res => {})
app.get('/path3', (req, res => {})
now I want to catch all routes, starting with api such as below and redirect them to their corresponding handler in express but not sure how to achieve that
/api/path1
/api/path2
/api/path3
I' assuming i can have a catch all api as below
app.all('/api/*', function (request, response, next) { //in a server.js file
//how can i call the corresponding paths here??
// looking for something to do forward to current-route.replace('api','')
// or something like that
})
Maybe a router-level middleware could solve your problem:
const router = express.Router();
router.get('/path1', (req, res => {});
router.get('/path2', (req, res => {});
router.get('/path3', (req, res => {});
app.use('/api', router);
Update:
Use redirect (not that much of a difference to your current solution; not tested):
app.all('/api/*', (request, response) => res.redirect(request.url.replace('/api', '')));
this worked for me, please let me know if there is a better way
app.all('/api/*', function (request, response, next) {
request.url = request.url.replace('/api','');
next();
})

How to isolate or fix no-response (browser hang) after calling passport.authenticate as middleware

I'm trying to use passport.authenticate('local') as middleware with passport-local-mongoose but it doesn't seem to pass control to the subsequent middlewares in my route.
I'm assuming there's an error but the following (err, req, res, next) middleware isn't being called so I'm wondering if I've misunderstood something basic about passport-local in general.
I've spent a few hours trying various things, searching here but I can't find a way to isolate my problem any further or get a better log of where control is going wrong in my route.
I've posted a small reproducible example to GitHub.
This is how I'm setting up BEFORE my routes:
// Get connected
mongoose.connect('mongodb://localhost/pass');
mongoose.Promise = global.Promise;
mongoose.connection.on('error', (err) => { console.error(err.message) });
// Basic user schema using nickname field as username
const Schema = mongoose.Schema;
const userSchema = new Schema({});
userSchema.plugin(passportLocalMongoose, { usernameField: 'nickname' });
const User = mongoose.model('User', userSchema);
// Initialise passport before routes
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);
app.use(passport.initialize());
And this is the route with my passport.authenticate:
app.post('/login',
(req, res, next) => {
console.log('login posted ok');
next();
},
passport.authenticate('local'),
(req, res) => res.send('login successful'),
(err, req, res, next) => {
console.log(err);
res.send('login unsuccessful');
}
);
There are other routes with the pug views and registration.
Registration works fine, in mongo db.users.find() show a good looking entry for the new user.
But my /login post route doesn't get beyond passport.authenticate.
The console.log gets triggered, so I know the route is being called.
Based on my limited knowledge of express and passport, I'm expecting one of those two following middlewares to be triggered, one on success and one if it fails.
Neither is triggering.
Best way to isolate is covered in the authenticate docs under "Custom Callback", I just didn't understand it originally.
NOTE: I've saved the following in the answer branch on my repo, as posted in the question.
app.post('/login',
(req, res, next) => {
console.log('login posted ok');
next();
},
(req, res, next) => {
console.log('authenticating...')
passport.authenticate('local', (err, user, info) => {
console.log(req, res, err, user, info);
next(err);
}) (req, res, next);
},
(req, res) => res.send('login successful'),
(err, req, res, next) => {
console.log(err);
res.send('login unsuccessful');
}
);
What I realised
passport doesn't consider authentication FAIL as an err
it just leaves user null
basically you need to give it success and failure redirects if you want to use middleware form, don't do what I did and try to handle err etc.

routes in exported router not available in app

I'm trying to export a router 'Accounts' to use in my app. The 'Accounts' router has the paths '/login' (POST), '/register'(POST), 'login' (GET), and '/logout' (POST). In my index app I am using the router with the path '/account'. So the paths should be:
/account/login (POST)
/account/login (GET)
/account/register(POST)
/account/logout (GET)
But when I call these paths they aren't found by the app:
How do I get the paths in the 'accounts.js' router to work in the 'index.js' app?
My file structure is like this:
my account.js file looks like this:
const express = require('express');
const passport = require('passport');
const Account = require('../models/Account');
const Branch = require('../models/Branch')
const router = express.Router({mergeParams: true});
const registerAccount = (req, res, next) => {
//register the account
};
const createUser = (req,res) => {
//create a user in another db
}
router.post('/register',
[registerAccount, createUser]);
router.get('/login', function(req, res) {
res.json(user);
});
router.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: 'account/login' }));
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
});
module.exports=router;
and my index.js looks like this:
// index.js
var express = require("express");
var bodyParser = require("body-parser");
var jwt = require("jwt-simple");
var auth = require("../auth/auth.js")();
var users = require("./users.js");
var cfg = require("../config.js");
const accountController = require('./account');
var app = express();
app.use(bodyParser.json());
app.use(auth.initialize());
app.use('/account',accountController);
app.get("/", function(req, res) {
res.json({
status: "My API is alive!"
});
});
app.post("/token", function(req, res) {
//some token stuff that doesn't matter here
});
module.exports = app;
For starters, you don't pass an array to a router.post(), so change this:
router.post('/register', [registerAccount, createUser]);
to this:
router.post('/register', registerAccount, createUser);
And make sure that registerAccount calls next() when it's done and wants createUser() to get called.
In the doc, for this syntax:
app.post(path, callback [, callback ...])
the brackets in [, callback] mean that parameter is optional. The brackets are not supposed to be used.

Express - How to dispatch the same path to different router file?

I'm making an app the will let different users see the different root page. Let's say there are two groups: admin and viewer. What I want to do is like:
var admin = require('./routes/admin');
var viewer = require('./routes/viewer');
app.get('/', function(req,res,...) {
if (req is admin) app.use('/', admin);
else app.use('/', viewer);
});
Is this possible, or I should redirect them to different paths? Thanks!
This needs to be done by redirecting a route to other route according to the requirement.
This can be done using below code:
var express = require('express');
var app = new express();
app.get('/', function(req, res, next) {
if(true) { //group check
res.redirect('admin');
} else {
res.redirect('viewer')
}
});
app.use('/admin', function(req, res, next) {
res.send('admin')
});
app.use('/viewer', function(req, res, next) {
res.send('viewer')
});
app.listen(3000);