Error: The res.end function is not recognized within the passport npm package

Help Needed: I am encountering this error and unable to resolve it. Can someone please check it out?

TypeError: res.end is not a function
    at allFailed (C:\Users\sam\OneDrive\desktop\WebDevPractice\secret-files\node_modules\passport\lib\middleware\authenticate.js:174:11)
    at attempt (C:\Users\sam\OneDrive\desktop\WebDevPractice\secret-files\node_modules\passport\lib\middleware\authenticate.js:180:28)
    at Strategy.strategy.fail (C:\Users\sam\OneDrive\desktop\WebDevPractice\secret-files\node_modules\passport\lib\middleware\authenticate.js:302:9)
    at Strategy.authenticate (C:\Users\sam\OneDrive\desktop\WebDevPractice\secret-files\node_modules\passport-local\lib\strategy.js:75:17)
    at attempt (C:\Users\sam\OneDrive\desktop\WebDevPractice\secret-files\node_modules\passport\lib\middleware\authenticate.js:366:16)
    at authenticate (C:\Users\sam\OneDrive\desktop\WebDevPractice\secret-files\node_modules\passport\lib\middleware\authenticate.js:367:7)
    at C:\Users\sam\OneDrive\desktop\WebDevPractice\secret-files\app.js:70:37
    at C:\Users\sam\OneDrive\desktop\WebDevPractice\secret-files\node_modules\passport-local-mongoose\index.js:247:28
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

// If anyone can review the register route, that would be much appreciated.

require('dotenv').config();
const bodyParser = require("body-parser");
const express = require("express");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require ("passport");
const passportLocalMongoose = require("passport-local-mongoose");

const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.set("view engine","ejs");
app.use(session({
    secret : "thisIsMyLitlleSecret",
    resave : false,
    saveUninitialized : false
}));
app.use(passport.initialize());
app.use(passport.session());

console.log(process.env.API_KEY);

mongoose.connect("mongodb://localhost:27017/userDB" , { useNewUrlParser: true , useUnifiedTopology: true });
mongoose.set("useCreateIndex", true);

const userSchema = new mongoose.Schema({
    email : String,
    password : String
});

userSchema.plugin(passportLocalMongoose);

const User = mongoose.model("User",userSchema);

passport.use(User.createStrategy());
 
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());


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

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

app.get("/secrets", function(req,res){
    if(req.isAauthenticated){
        res.render("secrets");
    }
    else{
        res.redirect("/login")
    }
})
app.get("/register", function(req,res){
    res.render("register");
});

app.post("/register", function(req,res){

  User.register({username : req.body.username}, req.body.password, function(err, user){
      if(err){
          console.log(err);
          res.redirect("/register");
      }
      else
      passport.authenticate("local")(res,req,function(){
          res.redirect("/secrets");
      });
  });

});



app.post("/login",function(req,res){

});

app.listen(3000,function(req,res){
    console.log("Server running on port 3000!!");
});

// Seeking suggestions on how to solve this issue.

Answer №1

There seems to be a small error in your code where "req" should come before "res". Here's the snippet of your code:

 passport.authenticate("local")(res,req,function(){
          res.redirect("/secrets");
      });

To fix this issue, simply switch the positions of request and response - it should be (req, res). It can be hard to notice the mistake at first glance. Here is the corrected version:

 passport.authenticate("local")(req, res, function(){
          res.redirect("/secrets");
      });

Answer №2

Passport typically serves as a middleman.

app.post(‘/signup’, passport.authenticate(‘local’), (req, res) => {
// 
}

I wonder why it's set for the signup route instead of login?

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

Updating a file using HTML5's FileWriter

I've been experimenting with the HTML5 FileWriter API in order to save my webapp's state. I have a snippet of JavaScript that regularly triggers the FileWriter.write function to achieve this, resulting in multiple calls to the write method over t ...

Looking to verify the validity of my email and phone number

Looking for some assistance in validating my email and telephone inputs for the contact form. The current code for email validation is incorrect, so I need help fixing it. It should be something like this: if(email.length == 0 || email.indexOf('@&apo ...

Encountering an issue with Apostrophe CMS version 2.65.0 when trying to launch the project

I am currently in the process of upgrading from version 2.62.0 to 2.65.0 for Apostrophe. As part of this upgrade, I have integrated the mongo driver-3 into my settings. However, I am encountering an error while running the project: (node:116248) Warning ...

Tips for hiding a child component while navigating to a different React route

I've implemented a dropdown feature in my BasketContents component (as discussed on this thread). It fades in and out when a button is clicked. However, I also want it to automatically close when the route changes by clicking a Link tag. For example, ...

An issue arose upon restarting my Eclipse software

Upon restarting my Eclipse, I encountered the following error message: "Plug-in com.android.ide.eclipse.adt was unable to load class com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor." As a beginner, could you advise me on how to addres ...

Resolve the Prototype_Pollution vulnerability detected by Checkmarx

When executing the code line window.location.search.substring(1) with the word 'substring(1)', an error related to Prototype_Pollution occurs. This error is caused by assigning external properties without proper validation, which can lead to obje ...

Enhancing your react-slick carousel with a captivating full-screen background

I need assistance with implementing a full screen slider using react-slick. I am facing difficulty in adding an image as the background. My code snippet looks like this: import image1 from "../assets/bg1.png" import image2 from "../ ...

Combining mongoose populate and pagination for optimal database querying techniques

For the full code, visit this link If you are looking to implement pagination with mongoose, there is a useful package available for that purpose. Although it is mentioned in this thread that populate can be used with pagination, I am facing difficulties ...

Selenium is encountering a validation error when selecting a value from a Drop Down menu

My current project involves automating website testing through selenium. I have encountered a scenario where I need to fill in a mandatory drop-down field. The code snippet I am using to select the drop-down value is as follows: select = Select(find_eleme ...

Uploading images in React JS by allowing users to paste images

Currently working on a chat application using React JS and I'm looking to enable image uploading when an image is pasted into the chatbox. How can I make this happen? Essentially, I am in need of: An event that will activate upon performing the "Pas ...

Exploring Collection Using Mongodb Search

I am looking to search a collection in MongoDB that includes: 'food_name' => 'fish' as well as 'room_features' => array ( 0 => 'Shower', 1 => 'Hairdryer', ), I have attempted t ...

Tips for fixing a GET 404 (not found) error in a MEAN stack application

While working on a profile page, I encountered an error when trying to fetch user details of the logged-in user: GET http://localhost:3000/users/undefined 404 (Not Found) error_handler.js:54 EXCEPTION: Response with status: 404 Not Found for URL: http:// ...

Retrieve the AngularJS scope object by using an alternate scope object as the identifier

As I loop through an array of person objects using ng-repeat, imagine the array looks something like this: [{ "display_name": "John Smith", "status": "part-time", "bio": "I am a person. I do people stuff.", }, { "display_name": "Jane Doe", "stat ...

Fading Out with JQuery

My page contains about 30 same-sized divs with different classes, such as: .mosaic-block, .events, .exhibitions, .gallery, .sponsors, .hospitality, .workshops, .lectures { background:rgba(0, 0, 0, .30); float:left; position:relative; overf ...

What is the best way to distinguish my REST API from my Express web application?

Currently, my Express application is serving a front-end web application. Can someone provide guidance on how to set up an API server with /api as the root endpoint? I'm looking to separate the API functionality from the main application. ...

Preventing file visibility in Three.js resource directory

Once a user clicks on a specific 3D model, I retrieve it from the server and render it in the browser using three.js. However, there is an issue when the user tries to access a model that is not free - they can easily view and download the STL file by go ...

The app crashed unexpectedly with an error code of MODULE_NOT_FOUND and no requirestack

While attempting to run nodemon with the command "run start" on macOS, I encountered the following error message. Unsure if the operating system is a factor. ERROR node:internal/modules/cjs/loader:926 throw err; ^ Error: Cannot find module '/User ...

using node and express to dynamically serve html templates stored in mongodb

Hey there, I'm a newbie when it comes to node and my goal is to create a basic blog. I'm aiming to navigate to /pages/:post in order to search a database for the specific "post" and then retrieve an HTML template file that can be utilized as a p ...

The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 7 ...

What is the process for linking an HTML document to another HTML document within a div using jQuery?

Check out my HTML code: <!DOCTYPE html> <html> <head> <title>Hilarious Jokes!</title> <meta charset="utf-8"> <link href="final%20project.css" rel="stylesheet"> <script src=" ...