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

Sending JSON Data from C# to External JavaScript File without Using a Web Server

Trying to transfer JSON data from a C# (winforms) application to a static HTML/JavaScript file for canvas drawing without the need for a web server. Keeping the HTML file unhosted is preferred. Without involving a server, passing data through 'get&ap ...

How can I configure nest.js to route all requests to index.html in an Angular application?

I am developing an Angular and NestJS application, and my goal is to serve the index.html file for all routes. Main.ts File: async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..&ap ...

Trouble with translating code from JavaScript to Python due to hash algorithm discrepancy

In an attempt to achieve consistent hash function results between JavaScript and Python, I encountered a roadblock when trying to convert my JavaScript function to its Python equivalent, resulting in unexpected outcomes. Original JavaScript Function: func ...

Incorporating HTML elements into a Jade template

Can HTML elements be passed into a jade file? For example, I want to insert text into the p element and nest some content inside the code element within the p element. JSON with string data var news = { one : { title : "Using JSON", body : "Us ...

Tips for highlighting HTML syntax within JavaScript strings in Sublime Text

Is there a Sublime package available for syntax highlighting HTML within JavaScript strings specifically? (Please note that the inquiry pertains to highlighting HTML within JS strings only, not general syntax highlighting.) Currently, I am developing Ang ...

Submitting modal form information using AJAX to PHP

As a novice in the realm of web programming, I find myself seeking some guidance to untangle a riddle. Regrettably, my grasp of the basics still leaves much to be desired. Within my main page, view.adminsettings.php, I've designated a Navigation DIV ...

Steps for correctly invoking a function based on input value conditions

Lately, I've been developing a new website geared towards serving as a platform for various travel agencies to showcase their tour packages. The homepage features a functional filter section that enables users to search for offers based on different ...

Transmit the canvas image and anticipate the AJAX POST response

I need to send canvas content to my API endpoint using ajax and wait for the response before moving on to the next function. Here is my current sending function: function sendPicture(){ var video = document.getElementById('video'); var canvas ...

Encountering issues while attempting to utilize pdf2json in a TypeScript environment

When attempting to import pdf2json (3.0.1) into my Node project using TypeScript, I encountered the following error: "Could not find a declaration file for module 'pdf2json'." I also tried installing @types/pdf2json for TypeScript but found tha ...

JQuery AJAX click event not triggering

I'm currently working on a project to create a dynamic website where users can update text fields directly from the site. However, I've encountered an issue on the 'admin' page where nothing happens when the button is pressed to set the ...

Don't initialize each variable within the constructor of a class, find a more efficient approach

I have a collection of JavaScript classes representing different models for my database. Each model contains attributes such as name, email, and password. Is there a more efficient way to create a new User instance without manually assigning values to ea ...

Sending Three.js meshes to a web worker through JavaScript

I have a collection of objects, which are meshes generated using Three.js, that I need to perform operations on within a web worker. My question is, how can I send these objects to the worker? My understanding is that there's a concept called transfe ...

How to Retrieve Element Property Values from the DOM with JavaScript

I am currently attempting to access the property of an element within my webpage. My main objective is to toggle a float property between left and right when a specific onClick event occurs. However, despite my efforts, I am facing challenges in even acces ...

Prevent users from navigating back after logging in on a Reactjs application

Is there a way to prevent users from using the browser's back button after redirecting them to another application in ReactJS? In my scenario, I have two applications running simultaneously. Upon successful login, I check the user type. If the conditi ...

Connecting a Database with NestJS and TypeORM: A step-by-step guide to establish a connection with TypeORM and ensure easy access to

Could someone please explain how to create a DB instance using TypeORM? I want it to be accessible like this service, but the Connection class is deprecated. import { Inject, Injectable } from '@nestjs/common'; import { Connection, Repository } ...

The media type provided is not supported for submitting form data to the spring server

I am facing an issue when trying to upload a file to a remote spring server through an API. Despite converting the data into form data, I keep receiving an unsupported media type error (415). Below is the HTTP post request using express: var FormData = r ...

Tips for adjusting the maximum characters per line in tinyMCE 5.0.11

I have an angular 8 application that utilizes tinyMCE, and I am looking to limit the maximum number of characters per line in the textArea of tinyMCE. My search for a solution has been unsuccessful so far despite extensive googling efforts. (image link: [ ...

Navigating a FormData object in javascript on a .NET WebAPI version 5.2.2

I am currently working on integrating webcam video recording upload using the example provided in this RecordRTC GitHub repo. However, I have encountered a compiling error when trying to use "Request.Files" as indicated in the screenshot below. The error ...

Error Encountered in NextJS - Hydration Unsuccessful

Currently, I am utilizing NextLink in my project to generate links. However, it appears that using NextLink is causing the following error: Hydration failed because the initial UI does not match what was rendered on the server. Upon inspecting the console ...

Is there a way to change the format of the date "Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time)" to JAN 01, 2020 in JavaScript?

I am currently retrieving the date from the database in the format of Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time), but I would like it to be displayed in the JAN O1,2020 format without using moment.js. Is there any alternative approach to ach ...