Marodian
Marodian

Reputation: 539

next() is not a function error Node.js

var express = require('express');
var app = express();

var middleware = {
    requireAuthentication: function(req, res, next){
        console.log("private route hit");
        next();
    }
};

app.use(middleware.requireAuthentication());


app.get('/about',

    function(req, res){
    res.send('You clicked on about!');

    }

);  
var projectDir = __dirname + '/public'; 
app.use(express.static(projectDir));
app.listen(3000), function(){
    console.log('Static service started');

};

I get the error (when trying to run the server) that next() is not a function. I've been following a tutorial on Nodejs and it works just fine for them. What is the issue I am having here?

Upvotes: 11

Views: 15610

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

This line:

app.use(middleware.requireAuthentication());

calls your method and passes its return value into app.use. You're not calling it with any arguments, so naturally the next parameter is undefined.

Get rid of the () so you're passing the function, not its result, into app.use:

app.use(middleware.requireAuthentication);
// No () here --------------------------^

Upvotes: 21

Related Questions