The login request through Express and Passport does not complete or finalize

I have implemented authentication in my express app using passport, passport-local and passport-jwt. The login code below generates a token which is then sent back via the response object. However, when attempting to login using Postman, the request never completes.

passport.use('login', localStrategyLogin);
passport.serializeUser(function (user, done) {
    done(null, user._id)
});

app.use(passport.initialize());
app.post('/login', (req, res, next) => {
    passport.authenticate('login', {session: false}, (err, user, info) => {
        if (err) {
            return next(err);
        }
        if (!user) {
            return next(new Error("Could not find user"));
        }

        req.login(user, {session: false}, (error) => {
            if (error) return next(error);

            const token = jwt.sign({_id: user._id, email: user.email}, JWT_SECRET, {expiresIn: JWT_EXPIRES});
            res.send({token});
        });
    })(req, res, next);
});

Login Strategy:

import { Strategy as LocalStrategy } from 'passport-local';
import User from "../models/User";

export const localStrategyLogin = new LocalStrategy({usernameField: 'email', passwordField: 'password'}, async function (email, password, done) {
try {
    const user = await User.findByLogin({email, password});
    if (user) return done(null, user);
} catch (e) {
    console.log(e.message);
}

return done(null, false, {message: 'Incorrect email or password.'});
});

Answer №1

The issue lies in your usage of next instead of returning a response.

return next(err);

Using 'next' passes control to the next middleware function, leaving the request hanging or open if not properly handled.

To address this, make the following modification:


return res.status(500).send(err);

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

Exploring the power of async/await in conjunction with loops

My JavaScript code is designed to extract content from HTML pages and perform a crawling operation. However, the issue arises with asynchronous execution due to a request function. I attempted to utilize Promises and async & await to address this probl ...

Expressing the power of multiple nested routers

Can multiple nested routers be implemented in an Express server? Imagine running a vehicle servicing business and wanting to organize the API into different services, each with its own set of actions: app.use('/clean', cleanRoutes); app.use(&apo ...

Tips for creating a cURL request with basic authentication in Laravel version 8

I am working with the PayPal Payout SDK and using the code below to obtain access tokens from the PayPal API. curl -v POST https://api-m.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: application/json" \ -H "Accept-Language: ...

Pictures failing to load in the MongoDB collection

I am facing an issue with uploading a form that includes an image to my mongodb database. While all the data is being stored correctly, the images are not visible in the database. I suspect this might be related to the error message 'typeError cannot ...

Steps for ensuring a promise is fulfilled in Node.js and Firebase

I've been struggling with this issue for quite some time now and can't seem to figure it out. g_globalList.once("value").then(function(tickList){ var multiPaths = []; tickList.forEach(function(ticker){ ticker.val().forEach(fu ...

Running socket.io and express simultaneously on an elastic beanstalk instance: A step-by-step guide

We are running an Elastic Beanstalk instance with both REST services and Socket.io. Our Express server is configured to start at port 80, while the Socket.io connection is set up on port 3001. Despite turning off the proxy from nginx to disable it, we ar ...

Exploring the variance in utilizing middleware callbacks with express.js

Here's a basic Express app: var express = require('express'); var app = express(); var router = express.Router(); function test (req, res, next) { } I'm currently exploring the differences in functionality between these two approach ...

Simultaneously Accessing Data from MongoDB and MySQL

I have been working on retrieving data from my MongoDB database, which contains chat conversations. The retrieval process is successful and I am getting the desired output. However, in my MongoDB database, I only store userIDs, so I need to fetch additiona ...

Retrieving inquiries associated with a specific tag on Stack Overflow

I'm part of a team of developers in my Discord community who are dedicated to helping others with their problems on Stack Overflow. Is there a way to create a bot that can automatically gather the latest question tagged with a specific keyword and s ...

Having trouble with socket.io functionality after deploying my application on Heroku platform

I encountered an issue with my app when deploying it to Heroku after working fine locally with socket.io. The problem lies in the socket setup on the client side, which is configured for localhost:5000. Unfortunately, I am unsure of how to resolve this. B ...

Continuous deployment with Node.js

Currently, my team and I are diving into a Node.js project for the first time. We've been running several node scripts in the forever demon, but we're finding it tedious to manually restart them every time there's an update or add a new scri ...

The UTF-8 encoded string in Node.js displays a mysterious black question mark

I am facing an issue with a CSV file that I receive from my supplier. They have encoded a string using UTF-8, resulting in black question marks appearing. Despite several attempts, I am unable to convert it back successfully. var common = req ...

Can the hash object generated by the NodeJS crypto module be safely reused?

If I need to hash a payload using nodejs, the crypto module can be utilized. It is possible to achieve this by: const crypto = require('crypto'); const payload = "abc123"; const hashObj = crypto.createHash('sha256'); const res ...

Postponing requests with the use of request and cheerio libraries

Here is the script I wrote to scrape data from multiple pages using request and cheerio modules: for (let j = 1; j < nbRequest; j++) { const currentPromise = new Promise((resolve, reject) => { request( `https://www.url${j}`, (error ...

Utilizing the output from a console.log in a webpage

Although the function I created is functioning properly and successfully outputs the value to my terminal onSubmit, I am facing difficulty in understanding why this code isn't updating my html. router.post('/index', function(req, res, next) ...

`Express.js Controllers: The Key to Context Binding`

I'm currently working on a project in Express.js that involves a UserController class with methods like getAllUsers and findUserById. When using these methods in my User router, I have to bind each method when creating an instance of the UserControlle ...

Navigating through directories to locate a 404 error page using Express

For my Express server, I have set up a 404 page like this: server.use(function(req, res, next) { res.status(404).sendFile('404.html', { root: __dirname + BASE }) }) The 404.html file is located in the website's root directory. It works p ...

unable to save the information to mongoDB

I've been attempting for the past 3 hours to save data from an HTML form to MongoDB using Node.js. When I click submit, it redirects to another page displaying the submitted data in JSON format, but it's not getting stored in the database. Here ...

Heroku local is designed to support only NodeJS applications, without any Angular framework or database connectivity

I'm currently facing two separate issues. When I run my app locally, it works fine, but it doesn't function properly on Heroku. Running "heroku local" opens the NodeJS app on localhost:5000 and connects to the local database. However, when attemp ...

Request for removal in Express.js

Currently in the process of developing a MERN-stack app, but encountering issues with the delete request function. Here is the relevant code snippet: Upon attempting to send a delete request via Postman, an error message is displayed. I have researched ...