最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - next() is not a function error Node.js - Stack Overflow

programmeradmin4浏览0评论
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?

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?

Share Improve this question edited Dec 22, 2016 at 17:06 Mike Cluck 32.5k13 gold badges83 silver badges94 bronze badges asked Dec 22, 2016 at 17:03 MarodianMarodian 5392 gold badges4 silver badges13 bronze badges 1
  • foo(bar()) always calls bar first and passes the return value to foo. requireAuthentication is not supposed to be called by you. – Felix Kling Commented Dec 22, 2016 at 17:08
Add a comment  | 

1 Answer 1

Reset to default 21

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 --------------------------^
发布评论

评论列表(0)

  1. 暂无评论