Providing Custom Params In Express Middleware - javascript

I am having a problem with my Node.js app. In short I want to pass custom parameters into my middleware function other than just req, res, and next.
Middleware file:
var DB = require('./DB.js');
function requirePermissions(e) {
console.log('nope')
}
module.exports = requirePermissions;
Route:
router.post('/posts', requirePermissions('post_creation'), function(req, res) {
var o = req.body,
title = o.post.title,
content = o.post.content;
res.send('made it');
});
I have confirmed that using function requirePermissions(req, res, next) {} will work, but I do not understand how to include my own parameters.

Your function requirePermissions should return another function which will be the actual middleware:
function requirePermissions(e) {
if (e === 'post_creation') {
return function(req, res, next) {
// the actual middleware
}
} else if (e === 'something_else') {
return function(req, res, next) {
// do something else
}
}
}
You can also do it like that:
function requirePermissions(e) {
return function(req, res, next) {
if ('session' in req) {
if (e === 'post_creation') {
// do something
} else if (e === 'something_else') {
// do something else
}
}
}
}

You can just create an anonymous function for your middleware that lets you call your actual function with some additional arguments:
router.post('/posts', function(req, res, next) {
requirePermissions('post_creation', req, res, next);
}, function(req, res) {
var o = req.body,
title = o.post.title,
content = o.post.content;
res.send('made it');
});
Or, you can use .bind() to preprend arguments:
router.post('/posts', requirePermissions.bind('post_creation'), function(req, res) {
var o = req.body,
title = o.post.title,
content = o.post.content;
res.send('made it');
});
This will call your requirePermissions() functions with four arguments like this:
requirePermissions('post_creation', req, res, next)

Related

Why do I need to pass (req, res, next) to bodyParser in Express?

I had originally been using bodyParser as so:
app.use(bodyParser.json());
However, now I want to conditionally use bodyParser:
app.use((req, res, next) => {
if (req.originalUrl === '/hooks') {
next();
} else {
bodyParser.json()(req, res, next);
}
});
When I try to remove (req, res, next), the parser does not work. That is,
app.use((req, res, next) => {
if (req.originalUrl === '/hooks') {
next();
} else {
bodyParser.json();
}
});
does not work.
Why do I need (req, res, next) after bodyParser.json()?
https://github.com/expressjs/body-parser/blob/master/index.js#L108
function bodyParser (options) {
var opts = {}
// exclude type option
if (options) {
for (var prop in options) {
if (prop !== 'type') {
opts[prop] = options[prop]
}
}
}
var _urlencoded = exports.urlencoded(opts)
var _json = exports.json(opts)
return function bodyParser (req, res, next) {
_json(req, res, function (err) {
if (err) return next(err)
_urlencoded(req, res, next)
})
}
}
Body parser is a middleware that needs access to res, req and next.
It parses your request using req and in order to pass control to the next middleware, it needs access to the next function.
Here app.use(bodyParser.json()); are passed (req, res, next) by default as
bodyParser.json() returns return function bodyParser (req, res, next) { .. }
so it becomes --> app.use(function bodyParser (req, res, next) { .. });
but in your case, you are creating a middleware by your self and you are responsible to pass the parameters to bodyParser so it can have access to the required arguments.
app.use((req, res, next) => {
if (req.originalUrl === '/hooks') {
next();
} else {
bodyParser.json()(req, res, next);
}
});
See how app.use works below
https://github.com/expressjs/express/blob/master/lib/application.js#L187-L242

How to pass a parameter to middleware function in Express JS?

// state edit route
app.get("/map/:symbol/edit", isLoggedIn, function(req, res){
State.findOne({symbol: req.params.symbol}, function(err, state){
if(err){
console.log(err);
} else
{
res.render("edit", {state: state});
}
});
});
In the above code snippet, isLoggedIn is the middleware function to check for authentication. Its definition is given below:
// middleware function
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/admin");
}
So, the question is, how to pass a parameter like a string, an integer or a path variable to the middleware function so that it can be used in the routing url ?
I had the same requirement and this approach works for me.
Middleware file validate.js
exports.grantAccess = function(action, resource){
return async (req, res, next) => {
try {
const permission = roles.can(req.user.role)[action](resource);
// Do something
next();
}
catch (error) {
next(error)
}
}
}
Use of middleware in route file. grantAccess('readAny', 'user')
router.get("/",grantAccess('readAny', 'user'), async (req,res)=>{
// Do something
});
Follow this approach, it might do the job for you
app.use(function(req, res, next){
console.log(req);
this.req = req;
// assign value like this
this.req.body.custom_data = ['zz', 'aaa', ....];
next();
});
app.get("/map/:symbol/edit", isLoggedIn, function(req, res){
State.findOne({symbol: req.params.symbol}, function(err, state){
if(err){
console.log(err);
} else {
res.render("edit", {state: state});
}
});
});
function isLoggedIn(req, res, next){
console.log(req.body);
if(req.isAuthenticated()){
return next();
}
res.redirect("/admin");
}
This is the way I'm using it, I take a little bit of Hardik Raval answer.
helpers.validateRole = (roles) => {
return async (req, res, next) => {
try {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[0]
if (token == null) return res.json({error:true, msg: "Unauthorized"})
const user = jwt.decode(token)
let isValid = false
roles.map((r,i)=>{
if (r === user.role){
isValid = true
}
})
if (isValid){
// User role is valid
next();
}else{
// User role is not valid
util.returnError("Unauthorized", res);
}
}
catch (error) {
next(error)
}
}
}
And I called like this.
router.get( "/requirements/list_of_requirements/:page/:rows", isAuthenticated, validateRole([6]), async (req, res) => {
//* All the logic
})

Can a POST request accept two callbacks and can the first pass data to the second?

I have the following .post() request:
const express = require('express');
const router = express.Router();
const search_controller = require('../controllers/searchController');
const result_controller = require('../controllers/resultController');
//Search Routes
router.post('/', search_controller.search_create_post);
module.exports = router;
Could I add a second callback to it so that the first callback is run, then the second callback as such:
router.post('/', search_controller.search_create_post, result_controller.result_create_post)
Would I need a next() somewhere in those create functions? And could I also pass data from the search_create_post callback to the result_create_post callback? I would want to pass in the newly created Search object's id.
My current search_controller.search_create_post function is a such:
exports.search_create_post = (req, res, next) => {
let newSearch = new Search({ search_text: req.body.search_text });
newSearch.save((err, savedSearch) => {
if (err) {
console.log(err);
} else {
res.send(savedSearch);
}
})
};
You might be able to use like this (based on how your functions are written):
// option A
router.post('/', search_controller.search_create_post, result_controller.result_create_post)
// options B
router.post('/', search_controller.search_create_post)
router.post('/', result_controller.result_create_post)
If search needs to pass data to result, you could set req.search_data in search_create_post and then get the value in result_create_post.
Take a look at https://expressjs.com/en/guide/using-middleware.html. There are a few good examples on this page.
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id)
next()
}, function (req, res, next) {
res.send('User Info')
})
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id)
})
based on your comment below:
You might be able to do this...
exports.search_create_post = (req, res, next) => {
let newSearch = new Search({ search_text: req.body.search_text });
newSearch.save((err, savedSearch) => {
if (err) {
console.log(err);
} else {
req.searchData = savedSearch;
}
next();
})
};

Express.js - wrap every middleware/route in "decorator"

I have Express.js instance and couple of routes which I want to wrap in some function. Example:
const wrapper = (route) => {
return (req, res, next) => {
let result = route(req, res, next);
// do some independent processing
}
};
app.get('/', wrapper((req, res, next) => {
// respond to request somehow
}));
While this works fine, I don't like the idea to explicitly call wrapper on every route or middleware which requires such processing.
Is there any way to be able to wrap every required route/middleware in certain wrapper (given that wrapper function can check that this route/middleware needs to be wrapped) implicitly (via Express.js extension, monkey-patching or some special middleware)?
UPDATE:
More solid example. Let's assume I want to make an async router functions. But I don't want to catch errors in each and every route function. So I wrap them up:
const wrapper = func => (req, res, next) => {
const promise = func(req, res, next);
if (promise.catch) {
promise.catch(err => next(err));
}
next();
};
app.get('/one', wrapper(async (req, res, next) => {
// respond to request somehow
}));
app.get('/two', wrapper(async (req, res, next) => {
// respond to request somehow
}));
app.get('/three', wrapper(async (req, res, next) => {
// respond to request somehow
}));
// and so on...
app.use((err, req, res, next) => {
// do something with intercepted error
});
This explicit wrapper around all routes is actually the thing I want to get rid of.
It turned out to be a bit of a PITA because, ultimately, Express doesn't propagate the return value of a route handler function.
This is what I came up with (a monkey-patch):
const Layer = require('express/lib/router/layer');
const handle_request = Layer.prototype.handle_request;
Layer.prototype.handle_request = function(req, res, next) {
if (! this.isWrapped && this.method) {
let handle = this.handle;
this.handle = function(req, res, next) { // this is basically your wrapper
let result = handle.apply(this, arguments);
// do some independent processing
return result;
};
this.isWrapped = true;
}
return handle_request.apply(this, arguments);
};
I would probably suggest using a similar approach as express-promise-router though, which implements a drop-in replacement for Express' Router. However, it's not implicit.
Why not just use next()?
You can add stuff on req like
app.get('/', (req, res, next) => {
req.somestupidfieldthatidontevenknowwhyinamedthisway = 42;
next();
});
app.get('/', (req, res, next) => {
//req.somestupidfieldthatidontevenknowwhyinamedthisway is now accessible as 42
var valueFromPreviousMiddleware = req.somestupidfieldthatidontevenknowwhyinamedthisway;
.....
});
You could wrap middleware and router as below
function wrapper(func) {
return function inner(req, res, next) {
const start = Date.now();
func(req, res, function () {
let elapsedMS = Date.now() - start
console.log('time elapsed for function ' + func.prototype.constructor.name + ' is ' + elapsedMS)
next.apply(this, arguments);
});
};
}
var originalAppUse = app.use;
app.use = function () {
lastArg = arguments.length - 1;
if (typeof arguments[lastArg] === 'function') {
arguments[lastArg] = wrapper(arguments[lastArg])
}
originalAppUse.apply(this, arguments)
}

HTTP requests in Express NodeJS

I have the following code from https://github.com/chjj/tty.js/:
this.get("/hola", function(res) {
iniciar();
});
function iniciar() {
self.init();
}
iniciar();
going to localhost:8080/hola, it does not load. localhost:8080 works perfectly. self.init() calls a function that, in turn, calls other functions. The problem seems to be the following called function:
Server.prototype.initMiddleware = function() {
var self = this
, conf = this.conf;
this.use(function(req, res, next) {
var setHeader = res.setHeader;
res.setHeader = function(name) {
switch (name) {
case 'Cache-Control':
case 'Last-Modified':
case 'ETag':
return;
}
return setHeader.apply(res, arguments);
};
next();
});
this.use(function(req, res, next) {
return self._auth(req, res, next);
});
this.use(term.middleware());
this.use(this.app.router);
this.use(express.static(__dirname + '/../static'));
};
According to express.js documentation:
// a middleware sub-stack which prints request info for any type of HTTP request to /user/:id
app.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
So, it seems that there are "conflicts" between first app.get and the others app.use or this.use. How can I solve that?
it's because you are not returnig anything and then the browser is polling this until it return something.
this.app.get("/hola", function(req, res) {
res.writeHead(200, {'content-type':'text/html'});
res.end('/*html code here*/');
});

Categories

Resources