简体   繁体   中英

'app.use() requires a middleware function' - Passport and Node Error

I'm trying to add local authentication to my node.js app. After following the tutorial on: https://scotch.io/tutorials/easy-node-authentication-setup-and-local I have run into error: "TypeError: app.use() requires a middleware function".

I think this is related to the app.use(indexRoutes) in my app.js file but I'm not sure how to fix this? Any help would be greatly appreciated.

Here is my code so far: app.js:

var express     = require('express'),
    session     = require("express-session"),
    bodyParser  = require('body-parser'),
    app         = express().use(bodyParser.json()), //creates express http server
    passport    = require('passport'),
    sanitizer   = require('express-sanitizer'),
    mongoose    = require("mongoose"),
    cookieParser    = require('cookieparser'),
    dotnev      = require('dotenv').config(),
    https       = require('https'),
    flash       = require('connect-flash'),
    fs          = require('fs'),
    config      = require('./config/config'),
    _           = require("underscore");

require('./config/passport')(passport);
var indexRoutes = require("./routes/index")(app, passport);

app.use(bodyParser.urlencoded({extended: true}));
app.use(sanitizer());
app.use(express.static(__dirname + "/public")); //tells express to serve the contents of the public directory

app.use(cookieParser);

//no longer need to specify that the view files are .ejs
app.set("view engine", "ejs");

app.use(session({
    secret: "akjjkjnisaiuu8998323jdkadsih892rhoisdfasl",
    resave: true,
    saveUninitialized: true,
    cookie: {
        maxAge: 1200000
    }
}));

app.use(passport.initialize);
app.use(passport.session());

app.use(flash());
app.use(indexRoutes);

mongoose.connect(process.env.MONGOLAB_URL, { useNewUrlParser: true });

index.js:

var express             = require("express"),
    router              = express.Router(),
    _                   = require("underscore"),
    User                = require("../models/user"),
    auth                = require("../routes/auth"),
    config              = require('../config/config'),
    freshbooks          = require("../modules/freshbooks"),
    quickbooks          = require("../modules/quickbooks");

module.exports = function(router, passport){
    //------------------------------------//
    //***------------ROUTES------------***//
    //------------------------------------//
    router.get("/", function(req, res) {
        res.render("landing");
    });

    router.get("/register", auth.optional, function(req, res) {
        res.render("register");
    });

    router.get("/login", auth.optional, function(req, res) {
        res.render("login");
    });

    router.get("/admin", isLoggedIn, function(req, res) {
        res.render('admin', {
            user : req.user // get the user out of session and pass to template
        });
    });

    //------------------------------------//
    //***-------------AUTH-------------***//
    //------------------------------------//
    router.post('/register', passport.authenticate('local-signup', {
        successRedirect : '/admin', // redirect to the secure profile section
        failureRedirect : '/register', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));

    router.post('/login', passport.authenticate('local-login', {
        successRedirect : '/profile', // redirect to the secure profile section
        failureRedirect : '/login', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));

    function isLoggedIn(req, res, next) {

        // if user is authenticated in the session, carry on 
        if (req.isAuthenticated())
            return next();

        // if they aren't redirect them to the home page
        res.redirect('/');
    }

    router.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });
}

Thanks in advance for any help!

In app.js

var { registerIndexRoutes } = require("./routes/index");
var indexRoutes = registerIndexRoutes(router, passport);
app.use(indexRoutes);

and index.js

const registerIndexRoutes =  function(router, passport){
    //------------------------------------//
    //***------------ROUTES------------***//
    //------------------------------------//
    router.get("/", function(req, res) {
        res.render("landing");
    });
   return router;//important;
}
module.exports = { registerIndexRoutes };

It will help you.

You're getting that error because, this function, module.exports = function(router, passport){ , is not a valid middleware.

From express docs : Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application's request-response cycle.

The syntax goes:

function(req, res, next) {
  // Implement the middleware function based on the options object
  next()
}

req : HTTP response argument to the middleware function, called "res" by convention.

res : HTTP request argument to the middleware function, called "req" by convention.

next : Callback argument to the middleware function, called "next" by convention.

When you invoked this function, function(router, passport){ :

var indexRoutes = require("./routes/index")(app, passport);

indexRoutes , contains the return value of function(router, passport) which does not return a middleware function (It returns undefined ).

Two ways you can solve the issue:

Change your import :

// remove this line and put the below instead
app.use(cookieParser);

// and modify and move your import
require("./routes/index")(app, passport);

Use Express router : Change your index.js like

// note your exports it's not a function, you're exporting this **router** object -> router = express.Router(),
module.exports = router;
//------------------------------------//
//***------------ROUTES------------***//
//------------------------------------//
router.get("/", function(req, res) {
  res.render("landing");
});

router.get("/register", auth.optional, function(req, res) {
  res.render("register");
});

...

And change your import to:

var indexRoutes = require("./routes/index");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM