Node - How To Access Req in POST Route Middleware - javascript

I'm new to Node and Express and I'm not sure how I can access req in a middleware function in a POST route. Do I need to pass it in as a parameter? There are other middleware functions in this route that access req but it is not being passed in. Overall, I'm guess I'm confused as to how req works...
The function I'm referring to is helpers.createPermissions()
My Route
app.post('/oauth/authorize/decision', login.ensureLoggedIn('connect/signin'), helpers.createPermissions(req), oauth2.server.decision());
The Function
exports.createPermissions = function(req) {
console.log(req);
};
The Error
ReferenceError: req is not defined

Middleware will always get passed three arguments: req, res and next.
So your middleware should look like this:
exports.createPermissions = function(req, res, next) {
console.log(req);
// TODO: make sure you eventually call either `next` or send back a response...
};
And you can use it like this:
app.post('/oauth/authorize/decision', login.ensureLoggedIn('connect/signin'), helpers.createPermissions, oauth2.server.decision());
In situations where you see middleware being called as a function, it's because you're not calling the middleware itself, but a function that's returning a middleware function. For example:
var myMiddlewareWrapper = function() {
// return the actual middleware handler:
return function(req, res, next) {
...
};
};
app.get('/', myMiddlewareWrapper(), ...);
This is usually done to pass extra options to the middleware handler (like with login.ensureLoggedIn()).

Related

usage of cors middleware vs custom middleware

Pardon me for this stupid question, but can someone explain me how the cors middleware work?
I accidentally called an auth middleware by adding brackets after it and it ran that middleware without even me requesting to that route.
I know that adding brackets after function invokes it but what is it with cors middleware that we add those brackets after it??
usage of cors middleware from docs:
app.get('/products/:id', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a Single Route'})
})
using auth middleware with () gives error:
app.get('/products/:id', auth(), function (req, res, next) {
res.json({msg: 'This is an authorized Route'})
})
usage of auth middleware without () works fine:
app.get('/products/:id', auth, function (req, res, next) {
res.json({msg: 'This is an authorized Route'})
})
Functions can return other functions, when you call the cors function using cors(), you get back a new function, that is used as the middleware function in app.get(). Your cors() example could be rewritten like so:
const corsMiddlewareFn = cors();
app.get('/products/:id', corsMiddlewareFn, function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a Single Route'})
})
Above we store the function that calling cors() returns in a variable called corsMiddlewareFn, and then we use that as middleware as part of the call to app.get(). Having cors() return a function is useful as it allows us to pass options to the cors() function so that the middleware function it returns can use those options accordingly.
On the other hand, your auth function most likely doesn't return a function, so auth itself is the middleware function you want to use, and not its return value which you would get when calling auth().
The cors module returns a function that takes optional configuration and returns the middleware.
The auth is already the middleware, not a function, so no need to call it.

expressJS - path values in App.use to mount a Middleware [duplicate]

I'm kind of new to express and node.js, and I can't figure out the difference between app.use and app.get. It seems like you can use both of them to send information. For example:
app.use('/',function(req, res,next) {
res.send('Hello');
next();
});
seems to be the same as this:
app.get('/', function (req,res) {
res.send('Hello');
});
app.use() is intended for binding middleware to your application. The path is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:
// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();
app.use('/subapp', require('./subapp'));
// ...
By specifying / as a "mount" path, app.use() will respond to any path that starts with /, which are all of them and regardless of HTTP verb used:
GET /
PUT /foo
POST /foo/bar
etc.
app.get(), on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:
GET /
And, the equivalent routing for your example of app.use() would actually be:
app.all(/^\/.*/, function (req, res) {
res.send('Hello');
});
(Update: Attempting to better demonstrate the differences.)
The routing methods, including app.get(), are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route').
Within each app.get() is a call to app.use(), so you can certainly do all of this with app.use() directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.
Examples:
For simple, static routes:
app.get('/', function (req, res) {
// ...
});
vs.
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
// ...
});
With multiple handlers for the same route:
app.get('/', authorize('ADMIN'), function (req, res) {
// ...
});
vs.
const authorizeAdmin = authorize('ADMIN');
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
authorizeAdmin(req, res, function (err) {
if (err) return next(err);
// ...
});
});
With parameters:
app.get('/item/:id', function (req, res) {
let id = req.params.id;
// ...
});
vs.
const pathToRegExp = require('path-to-regexp');
function prepareParams(matches, pathKeys, previousParams) {
var params = previousParams || {};
// TODO: support repeating keys...
matches.slice(1).forEach(function (segment, index) {
let { name } = pathKeys[index];
params[name] = segment;
});
return params;
}
const itemIdKeys = [];
const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
app.use('/', function (req, res, next) {
if (req.method !== 'GET') return next();
var urlMatch = itemIdPattern.exec(req.url);
if (!urlMatch) return next();
if (itemIdKeys && itemIdKeys.length)
req.params = prepareParams(urlMatch, itemIdKeys, req.params);
let id = req.params.id;
// ...
});
Note: Express' implementation of these features are contained in its Router, Layer, and Route.
Simply
app.use means “Run this on ALL requests”
app.get means “Run this on a GET request, for the given URL”
app.use is the "lower level" method from Connect, the middleware framework that Express depends on.
Here's my guideline:
Use app.get if you want to expose a GET method.
Use app.use if you want to add some middleware (a handler for the HTTP request before it arrives to the routes you've set up in Express), or if you'd like to make your routes modular (for example, expose a set of routes from an npm module that other web applications could use).
app.get is called when the HTTP method is set to GET, whereas app.use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.
Difference between app.use & app.get:
app.use → It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.
app.get → It is only for handling GET HTTP requests.
Now, there is a confusion between app.use & app.all. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests.
But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.
app.use() → It takes only one callback.
app.all() → It can take multiple callbacks.
app.use() will only see whether url starts with specified path.
But, app.all() will match the complete path.
For example,
app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject
app.all( "/book" , handler);
// will match /book
// won't match /book/author
// won't match /book/subject
app.all( "/book/*" , handler);
// won't match /book
// will match /book/author
// will match /book/subject
next() call inside the app.use() will call either the next middleware or any route handler, but next() call inside app.all() will invoke the next route handler (app.all(), app.get/post/put... etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.
In addition to the above explanations, what I experience:
app.use('/book', handler);
will match all requests beginning with '/book' as URL. so it also matches '/book/1' or '/book/2'
app.get('/book')
matches only GET request with exact match. It will not handle URLs like '/book/1' or '/book/2'
So, if you want a global handler that handles all of your routes, then app.use('/') is the option. app.get('/') will handle only the root URL.
There are 3 main differences I have found till now. The 3rd one is not so obvious and you may find it interesting. The differences are the same for the express router. That means router.use() and router.get() or other post, put, all, etc methods has also same difference.
1
app.use(path, callback) will respond to any HTTP request.
app.get(path, callback) will only respond to GET HTTP request. In the same way, post, put, etc will respond to their corresponding request. app.all() responds to any HTTP request so app.use() and app.all() are the same in this part.
2
app.use(path, callback) will match the prefix of the request path and responds if any prefix of the request path matches the path parameter. Such as if the path parameter is "/", then it will match "/", "/about", "/users/123" etc.
app.get(path, callback) Here get will match the whole path. Same for other HTTP requests and app.all(). Such as, if the path parameter is "/", then it will only match "/".
3
next('route') doesn't work on the middleware/callback functions of app.use(). It works only on app.get(), app.all() and other similar function of other HTTP requests.
According to express documentation:
next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.
METHOD is the HTTP method of the request that the middleware function
handles (such as GET, PUT, or POST) in lowercase.
From here we will use the keyword METHOD instead of get, post, all, etc.
But what is next('route')?!
Let's see.
next('route')
we see, app.use() or app.METHOD() can take several callback/middleware functions.
From the express documentation:
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
So we see each middleware functions have to either call the next middleware function or end the response.
And this is same for app.use() and app.METHOD().
But sometimes in some conditions, you may want to skip all the next callback functions for the current route but also don't want to end the response right now. Because maybe there are other routes which should be matched. So to skip all the callback functions of the current route without ending the response, you can run next('route'). It will skip all the callback functions of the current route and search to match the next routes.
For Example (From express documentation):
app.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next route
if (req.params.id === '0') next('route')
// otherwise pass the control to the next middleware function in this stack
else next()
}, function (req, res, next) {
// send a regular response
res.send('regular')
})
// handler for the /user/:id path, which sends a special response
app.get('/user/:id', function (req, res, next) {
res.send('special')
})
See, here in a certain condition(req.params.id === '0') we want to skip the next callback function but also don't want to end the response because there is another route of the same path parameter which will be matched and that route will send a special response. (Yeah, it is valid to use the same path parameter for the same METHOD several times. In such cases, all the routes will be matched until the response ends). So in such cases, we run the next('route') and all the callback function of the current route is skipped. Here if the condition is not met then we call the next callback function.
This next('route') behavior is only possible in the app.METHOD() functions.
Recalling from express documentation:
next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.
Since skipping all callback functions of the current route is not possible in app.use(), we should be careful here. We should only use the middleware functions in app.use() which need not be skipped in any condition. Because we either have to end the response or traverse all the callback functions from beginning to end, we can not skip them at all.
You may visit here for more information
app.use gets called every time a request is sent to the server.
Only thing is we should call it before handling get, put, post etc. requests
app.use(middleware);
function middleware(req, res, next)
{
console.log("Came in middleware function without arrow");
next();
}
app.get gets called only for get requests for given path.
app.get('/myget', myget_function);
function myget_function(req, res)
{
console.log("Came in function myget");
res.send('Hello World! from myget');
}
app.post gets called only for post requests for given path.
app.post('/mypost', mypost_function);
function mypost_function(req, res)
{
console.log("Came in function mypost");
res.send('Hello World! from mypost');
}

Can I pass the parameters (req, res, next) of a function to another function?

I searched a little bit but I did not find what I am searching for.
I have Node application and two functions:
router.get('/get/user-relevant-data', (req,res,next)=>{
//some code is executed here
return res.status(200).json(userRelevantData)
})
router.get('/get/updated-user', (req,res,next) => {
// I want to call '/get/user-relevant-data' and assign the returned object to another variable
let userRelevantData = // how to call the function here correctly?
})
How would I do such things (if it's feasible) or should such code be avoided? If such code should be avoided, what else could I do except putting the code of the one function into the other.
you can change the way you set up router in that way you can apply as many middlewares as you want like this:
const middleware1 = require("....") //adress to the file your middleware is located
const middleware2 = require("....") //adress to the file your middleware is located
router.get('/directory', middleware1, middleware2 )
and in another file you define middlewares in this way :
exports.middleware1 = (req, res, next) => {
//do some coding
req.something= someDataToPass
next()
//you add the data you want to pass to next middleware to the req obj
// and then access that in the next middleware from the req object then
// call next to run the next middleware
}
then in another file or the same file you type another middleware like this:
exports.middleware2 = (req, res, next) => {
//do some coding
data = req.something
//get data from last middeleware
res.json({})
}
and at the same time you have access to all the req data in both middlewares

ExpressJS routing with different parameters

I have two routes : app.use serves the static files.
app.use('/test', earlyAccess(), express.static(path.join(__dirname, staticFolder)))
app.get("/test", callback);
app.get("/test/:id", callback);
// Here is the callback
var fileStream = fs.createReadStream(staticFolder + '/test.html');
fileStream.on('open', function () {
fileStream.pipe(res);
});
From the browser, if I call localhost:80/test/1 - works fine.
but if I call localhost:80/test - it gets redirected to main page. In the server console, I got 304 warning.
How to use routes based on parameter in expressjs?
Try to use res.sendFile instead fs.createReadStream, something like:
res.sendFile('test.html');
You can check for request parameters within the callback,
app.get('/test', callback);
app.get('/test/123', callback);
// callback
if(req.params.second) {
// code for route with param. - /test/123
}
else {
// code for route without param. - /test
}
Parameters in the request are stored in req.params as
{first:'NameOfRoute', second:'NextParam'} ...
So here,
{first:'test', second:'123'}
you can try it like this:
app.use("/test/*", (req, res, next) => {
// your callback(req, res);
next();
});
app.get("/test/:id", callback);
app.use, mean you can write a middleware, and it will call next();

ExpressJS > router middleware > passing variable req.foo via redirect not working

Let's say I have this:
a) 2 routes with 1 middleware function each and a callback function:
router.post('/foo', fooCtrl, function(req, res)
{
res.redirect('/bar');
});
router.get('/bar', barCtrl, function(req, res)
{
res.end('finished');
});
b) 2 middleware function expressions
fooCtrl = function(req, res, next)
{
req.foo = 'foo';
next();
};
barCtrl = function(req, res, next)
{
console.log(req.foo); // output is 'undefined'
next();
};
As you can see, in the fooCtrl I'm setting a variable req.foo - and in this scope it is set than... but I'm not able to call this variable in the barCtrl-scope.
Isn't the req object passed by reference?
Any suggestions or best practices?
The purpose of this is to pass a token after login from the login-controller to an admin-controller .. something like that.
That is the expected behaviour. req object is created anew for each new request and your redirection i.e. res.redirect('/bar') results in a new request.
Solution:
You may use some package e.g.connect-flash which stores variables in a temporary session object, which can be used only once. You need to set required values in your flash objects before redirecting. Then after redirection, you will be able to get the saved values from the flash object itself.

Categories

Resources