Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 667
Marodian Avatar asked Dec 22 '16 17:12

Marodian


People also ask

What is next () in node JS?

The next() method returns an object with two properties done and value . You can also provide a parameter to the next method to send a value to the generator.

What is next () in JS?

Next.js is a flexible React framework that gives you building blocks to create fast web applications.

Do you need node JS for next?

node is the basis for next, without node there will be no next. NextJS simply provides an easy way to write server side ReactJS code, and have it rendered on the server and the browser.

What is type error in node JS?

The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. A TypeError may be thrown when: an operand or argument passed to a function is incompatible with the type expected by that operator or function; or.


1 Answers

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 --------------------------^
like image 83
T.J. Crowder Avatar answered Oct 13 '22 07:10

T.J. Crowder