JavaScript middleware not detected

Currently, I have begun self-learning and encountered a roadblock that I can't seem to overcome.

I am attempting to design a login page and delving into middleware for the first time.

The error message I'm facing is: throw new TypeError('app.use() requires a middleware function')

Error Type: app.use() requires a middleware function

Below is the code snippet:

var express               = require("express"),
    mongoose              = require("mongoose"),
    passport              = require("passport"),
    bodyParser            = require("body-parser"),
    User                  =require("./models/user"),
    LocalStrategy         =require("passport-local"),
    passportLocalMongoose = require("passport-local-mongoose");


mongoose.connect("mongodb://localhost:27017/auth_demo_app", { useUnifiedTopology: true },{ useNewUrlParser: true });
var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));

app.use(require("express-session")({
    secret: "Neno is the best and cutest dog in the world.",
    resave: false,
    saveUninitialized: false
}));
app.use(new LocalStrategy(User.authenticate()));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(User.serializeUser()); // Encoding the session
passport.deserializeUser(User.deserializeUser()); // Decoding the session

// =========
// ROUTES 
// =========

app.get("/", function(req, res){
    res.render("home");
});
app.get("/secret", function(req, res){
    res.render("secret");
});

// ===========
// Auth ROUTES
// ===========

// Show Signup Form
app.get("/register", function (req, res){ // req - request / res - response
    res.render("register");
});
//handling USER SIGN UP
app.post("/register", function(req, res){
    req.body.username
    req.body.password
    User.register(new User({username: req.body.username}), req.body.password, function(err, user){
        if(err) {
            console.log(err);
            res.render("register");
        } else {
            passport.authenticate("local")(req, res, function(){
                res.redirect("secret");
            })
        }
    });
})

//handling USER LOG IN / LOGIN ROUTES

app.get("/login", function (req, res){
    res.render("login");
});
//login logic
//middleware
app.post("/login", passport.authenticate("local", {
    successRedirect: "/secret",
    failureRedirect: "/login"
}),function(req, res) {
});
app.listen(3000, function (){
    console.log("Server Started......");
})

Answer №1

Remember to assign the strategy to passport, not the app.

Instead of using

app.use(new LocalStrategy(User.authenticate()));

Use

passport.use(new LocalStrategy(User.authenticate()));

Furthermore, consider passing a function

new LocalStrategy(User.authenticate)
instead of its output. Unless, of course, you have designed it to return a callback (difficult to determine without seeing your code).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to Change Background Color on Button Click

The button press does not result in a change of the background color. What could be causing this issue? var body = document.getElementsByTagName("body"); var bgbutton = doucument.getElementById("bgchange"); bgbutton.onclick = function() { body.style.b ...

What is the mechanism behind control flow returning in a series of Express middleware functions?

I have some inquiries regarding Express middleware chaining that I'd like to address in this consolidated post since they are interconnected. Q1: While working with a middleware function, if I use send() on the Response, pass it to the next function, ...

Finding an element based on its styling attribute, such as its position on the left or right side

One particular block that caught my eye is the slider element: <div id="sliderDispo" class="slider slider-dispo" data-slider-init="" data-slider-color="#0077b5 #EC6E31 #E40B0B" data-slider-step="33" > <div class="slider__interval" ...

Instructions on incorporating domains into next.config.js for the "next/image" function with the help of a plugin

Here is the configuration I am currently using. // next.config.js const withImages = require("next-images"); module.exports = withImages({ webpack(config, options) { return config; }, }); I need to include this code in order to allow images from ...

Activating the delete event trigger for a tinyMCE object

How can I create a function that activates when a user deletes an object in tinyMCE? I want to remove uploaded images from a cache folder whenever a user deletes an image from the tinyMCE editor. If they upload an image and then delete it, I would like an ...

Receiving an item in place of a true/false indicator

I wrote an asynchronous function that validates the permission status on a device. Here is the function: checkPermission = async () => { const allowed = await requestNotifications(['alert', 'sound']).then((res) => { if ...

What are the steps to resolving an issue in a Jest unit test?

In my ReactJs/Typescript project, I encountered an issue while running a unit test that involves a reference to a module called nock.js and using jest. Initially, the import statement was causing an error in the .cleanAll statement: import nock from &apos ...

What is the best way to extract a specific line from a command using a child process in a Node.js environment?

I am attempting to retrieve the disk space of a virtual machine using a child process in Node.js. Below is the code I have written for this purpose: const { exec } = require('child_process'); function diskSpace(err, result) { exec('df - ...

How do three buttons display identical content?

I have three buttons on my website, each with its own unique content that should display in a modal when clicked. However, I am experiencing an issue where regardless of which button I click, the same content from the last button added is displayed in the ...

Ideal location to detect web browser and display or conceal a division

I am looking to display a div using either the ng-if or ng-show/hide directives if the user accesses the page through a specific browser, such as Chrome/Chromium. However, I am unsure of the optimal location to place this functionality. The JavaScript cod ...

Implementing an HTTP GET API in GraphQL Apollo Server version 2.0

I'm currently working on a project that involves using Apollo Server v2.0 without middleware. I need to incorporate a feature that allows for file downloads through a HTTP GET endpoint. Is there a method to create an API endpoint for this purpose with ...

What is the best way to send form data to MongoDB using React?

I am seeking guidance on how to pass the values of form inputs to my MongoDB database. I am unsure of the process and need assistance. From what I understand, in the post request within my express route where a new Bounty is instantiated, I believe I need ...

"The specified engine was not found" - Sending JSON only

I am encountering an error that I cannot seem to resolve. I am perplexed as to why this error is occurring, as I am not using res.render and I have not specified a view engine, which I do not require, as I am handling all routing from the front end using A ...

issue occurred when executing the command "grunt serve:dist"

I utilized the mean stack seed by following this link: https://github.com/angular-fullstack/generator-angular-fullstack However, when attempting "grunt serve:dist," I encountered the following error: Running "ngAnnotate:dist" (ngAnnotate) task >> 2 ...

Generating separators in every third row using an array of card elements

https://i.stack.imgur.com/PIMR2.png Hey everyone, I'm working on creating a Divider for every row of 3 items. Currently, my setup only handles two sets of rows, but there could be an unlimited amount of rows that need this divider. I am using slice t ...

Using Lodash to Substitute a Value in an Array of Objects

Looking to update the values in an array of objects, specifically the created_at field with months like 'jan', 'Feb', etc.? One way is to loop through using map as demonstrated below. However, I'm curious if there's a more co ...

Issue: The module 'xdl' cannot be located while executing the command "npm start" in React Native

Recently, I delved into learning React Native through an online Udemy course. Everything was going smoothly until a few days back when I encountered an error message after running the simple "npm start" command. Despite trying various solutions like reinst ...

I'm currently leveraging Vue.js and Python Flask for my backend development. I'm looking to establish some local variables. What is the best way to accomplish this?

Here is my Vue js file where I am utilizing two URLs from localhost. My goal is to create a configuration file that will allow me to make changes in one place and have those changes reflected throughout. <template> <div> <div class="glob ...

Bootstrap 4: The mystery behind why the popover fails to appear inside a scrollable dropdown

Is there a way to replicate the behavior of Bootstrap 3 dropdowns with scrollbars on hover and popovers in Bootstrap 4? It seems that setting overflow:hidden; for scrolling functionality in dropdown menus also hides the popover. I have tried using containe ...

Tips for adjusting the value of a textbox up and down

I am facing an issue with my booking flight form that is supposed to take input from users regarding the number of travelers. I have three textboxes for Adult, Children, and Infants respectively, along with a main textbox to display the final result. Howev ...