Skip to content

Instantly share code, notes, and snippets.

@rg1220
Last active April 9, 2019 06:38
Show Gist options
  • Save rg1220/79c3c3930c34b7c11b55 to your computer and use it in GitHub Desktop.
Save rg1220/79c3c3930c34b7c11b55 to your computer and use it in GitHub Desktop.
Here's a simple gist for getting a user before another route handles the actual command.
var express = require('express');
var router = express.Router();
router.use(function (req, res, next) {
User.findOne(1234, function(err, user) {
if (err) {
console.log(err);
res.json({ error: 'There was an error' });
}
else {
res.locals.user = user;
next();
}
});
});
router.get('/get/id', function (req, res) {
res.json({ id: res.locals.user.id });
});
router.get('/get/name', function (req, res) {
res.json({ name: res.locals.user.name });
});
...
app.use('/api/v1', require('./api.js'));
....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment