I am working through an excellent tutorial on using the Node.js package Passport (link) for user authentication, and I ran into a piece of code that I really don't understand:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user : req.user // get the user out of session and pass to template
});
});
My question is with the isLoggedIn parameter. I looked at the official site, and did some google searches, but nowhere does it say that you can pass three parameters into app.get. I've only ever seen two. What is this third (optional, I assume) parameter?
I'm not asking about the isLoggedIn itself, but rather, about the fact that it's a third parameter I've never seen passed into app.get() before.
It's called middleware, and it's called before the third parameter (the callback).
Middleware functions examples: access checks, check to see if user is logged in before passing resources, and such.
It's in the express documentation: http://expressjs.com/en/5x/api.html#app.get
The syntax is:
app.get(path, callback [, callback ...])
i.e.
app.get(path, ...callback)
The syntax includes taking in a path as the first parameter, followed by as many middleware (having access to the request and response) callback functions as you desire. It's not limited to one. They are asynchronous and chained together by calling the next() parameter.
function callbackOne(req, res, next) {
//some code
next();
}
function callbackTwo(req, res, next) {
//some code
res.render();
}
app.get(path, callbackOne, callbackTwo)
So, in your case, the isLoggedIn parameter is simply just another middleware function that eventually calls next() if the user is logged in to bring execution to the third parameter.
Related
Middleware functions have a signature function (req, res, next), but in Express the next() call does not contain arguments. How is this so? See the following example from the
sample documentation
var express = require('express')
var app = express()
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
It certainly could be the case that a wrapping function is created that under-the-hood binds the arguments, allowing for a call with no additional parameters, but the documentation seems to indicate that the next parameter is called as-is, which does not make sense.
The docs describe the third argument, conventionally named next, as
Callback argument to the middleware function, called "next" by convention.
You can think of it similar to the conventional node.js callback-style argument provided to most async functions (without promises). When your middleware function is done doing its sync or async work, it should call next to indicate to the express router that it is done executing. This argument could be called done or callback, as we often see in other node.js libraries and examples, but is called next to provide a hint to the developer that the middleware chain will continue execution (other middleware may be called after this one).
Do we use it only in middlewares or the functions with no routes? I have used it in my authentication file...
function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
} else {
req.flash('error_msg' , 'Please login First...')
res.redirect('/users/login');
}
}
You execute it in order to execute the next middleware in the pipe. If you don't execute it manually, you're probably passing it on to a different module that executes it for you. Otherwise, if you don't execute next, you cut the "pipe" short i.e. yours is the last middleware that runs.
In your case it makes perfect sense to call next() when the user is authenticated. That passes the control to the next piece of middleware. It also makes sense not to call next() in the case that you've already established that the user is not authenticated, since in most cases you don't want the rest of the middleware in the "pipe" to execute.
So yes, next() is used by middleware, or modules intended to be called by middleware.
I hope that answers your question.
If you talking about Express framework here - next function is just a callback telling that this particular middleware handler should execute next operation in Express middleware chain.
If you define any handler with signature someHandler(req, res, next) and register it with app.use, it will become a part of that chain. Essentially it just a special callback function - disregarding the purpose of the function itself - route controller, authentication, body parser, etc.
I understand the essence of callback functions in that the function is executed again after being passed as the parameter to another function. However, I'm confused as to where the variables inside the callback function come from as shown in the following node.js example:
router.get('/', function(req, res){
res.render('index', {});
});
How do the variables req and res get populated? An example explaining how I can just call res.render(...) without declaring res myself would be greatly appreciated.
They come from the same place they come from when a normal non callback function is invoked, at invocation time.
If you have this function,
function add (a, b) {
return a + b
}
You're fine with knowing that a and b come from when you invoke add,
add(1,2)
and it's the same principle with callbacks, don't let your brain get all twisted just because it's getting invoked later.
At some point the function you pass to router.get is going to be invoked, and when it does, it will receive req and res.
Let's pretend the definition for router.get looks like this
router.get = function(endpoint, cb){
//do something
var request = {}
var response = {}
cb(request, response) // invocation time
}
In the case of your example, it's just up to node to pass your function request and response whenever .get is invoked.
The whole point of the callback is that the invoked function calls it back.
In the case of router.get, it will insert the route (path, method, callback) in a lookup table; when a request comes in, Express will construct the response object, match the request's path and method against all the entries in the lookup table, take the callback from the matching entry and invoke callback(request, response) (passing the detected request and created response).
They get populated by whatever code is calling the callback. In your example, this is something inside the Express framework, though Express uses the node http library under the hood and adds additional functionality to the request and response objects provided by it.
But in code you write you can create a callback function signature that takes whatever params you want.
Example controller function:
getArticles: function(req, res) {
Articles.find({}).exec(function(err, articles) {
res.json(articles) // I guess this part is asynchronous
// next() here?
})
}
I am used to call next() at the end of an asynchronously executed block of code. That seems to be different in Sails.js. Can somebody explain this to me?
Because res.json() in this instance is the last thing you're asking the server to do. There is no next now.
The next() convention in this case is due to the fact that sails runs on top of express.js. Next() is the pattern in how express runs through its list of middleware. That is why you would use next() in your policies and such because they are middlewhere. res.json() however is at the end of the chain, so their is no need to call next().
If you're still confused, google express middleware next()
To use return? This example below shows why you would want to use return despite it not being needed. By using return we ensure that res.json('otherStuff') does not execute.
getArticles: function(req, res) {
Articles.find({}).exec(function(err, articles) {
if(true) return res.json(articles)
res.json('otherStuff')
})
}
I recently read a blog in Nodejitsu and I am wondering how this piece of code works.
var fs = require('fs'),
http = require('http'),
httpProxy = require('../lib/node-http-proxy');
module.exports = function (logging) {
// Code here is run when the middleware is initially loaded.
var logFile = fs.createWriteStream('./requests.log');
return function (request, response, next) {
// Code here is run on each request.
if (logging) {
logFile.write(JSON.stringify(request.headers, true, 2));
}
next();
}
}
And the explanation given for this piece of code is:
This middleware is for very simple logging - it will write the headers of each request to a log file.
the above module exported can be used as,
httpProxy.createServer(
require('./example-middleware')(true),
8000, 'localhost'
).listen(9000)
How is the code in the above method with next() invoked in every request? The usage is pretty simple: require the above module and it gets invoked every time.
I'll simplify the actual process but the gist of it:
When a request comes in, node passes the request and response object to the first middleware in the middleware stack. If that middleware sends a response or closes the connection in any way, then subsequent middleware are not called. Otherwise, that middleware has to tell node it's finished doing it's job to keep on moving through the middleware stack, so you call next() within your middleware to tell it to continue processing middleware.
Okay, so this is a pretty common thing. What this module contains is a single function, specified by this line, where we set module.exports to a function, module.exports = function (logging) {. The function returned by the module (and therefore returned by require()) returns another function, which is the middleware for the HTTP proxy (this middleware allows you to transforms the request). This middleware function gets called for every HTTP request made to the server. Quickredfox's answer provides a fairly good explanation of middlewares.
So the require('./example-middleware')(true) actually calls the function assigned to module.exports, but does not call the function inside that, which is returned immediately and passed as a middleware into the httpProxy.createServer function. This is a good way to set up some options for your middleware using closures. If you have any more questions, feel free to comment. :D