Express and Passport encounter a Bad Request Error message

I've created a simple express API that utilizes passport.js for authentication:

const express = require("express");
const app = express();
const LocalStrategy = require("passport-local").Strategy;
const passport = require("passport");

passport.use(
  new LocalStrategy(function (username, password, done) {
    if (username === "admin" || password === "password") {
      // Authentication succeeded
      return done(null, { id: 1, username: "admin" });
    } else {
      return done(null, false);
    }
  })
);
app.use(passport.initialize());
app.get("/", (req, res) => {
  res.send("ok");
});
app.post("/login", passport.authenticate("local"), function (req, res) {
  res.json({ message: "Authentication successful" });
});
app.listen(3000, () => {
console.log(`http://localhost:3000/`);
});  

However, when I make a request to '/login' like this:

POST http://localhost:3000/login
    Content-Type: application/json

    {
        "username":"admin",
        "password":"password"
    }

The response says Bad Request

I'm still learning Express.js and struggling to find helpful resources. Any assistance would be greatly appreciated.

Answer №1

Looks like there is a small mistake in your /login route:

//app.post("/login", passport.authenticate("local"), function (req, res) {
//  res.json({ message: "Authentication successful" });
//});

app.post("/login", (req, res) => {
    passport.authenticate("local", (err, user, info) => {
      // if (err) {
      //   return res.status(500).json({ message: "Authentication error" });
      // }
      // if (!user) {
      //   return res.status(401).json({ message: "Authentication failed" });
      // }
      res.json({ message: "Authentication successful" });
    })(req, res);
});

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

Extract the content from the division and set it as the image source

Looking for a way to retrieve the content from a div and insert that into the 'src' parameter of an image. Working on a project where JSON is used to load translation files, preventing me from loading images directly, but I want to at least load ...

Changing divider color in Material-UI with React

I need some assistance with changing the color of the divider component from the material ui framework. I have successfully changed colors for other components using the useStyles() method like this: const useStyles = makeStyles(theme => ({ textPad ...

What is the process of converting the timing from my stopwatch to a standard time format?

I am currently working on a stopwatch project where I log the time into an array. However, when I try to use Math.min(array) or Math.max(array), it returns NaN (not a number). The time format for the stopwatch is like 00:00:15.91 which is not recognized as ...

How can a Vue component interact with a JavaScript method?

Within my main.js file, I have configured Vue as follows: window.Vue = require('vue'); Vue.component('my-component', require('./components/MyComponent.vue')); const app = new Vue({ el: '#app', }); Additionall ...

Leveraging the arguments object within function declarations

Could someone explain why the foo function functions properly? function foo (x,y) { return arguments.length; } However, when I call the boo function with arguments, it returns an error saying undefined is not a function. function boo (c,d) { return ...

Excessive form inputs extend beyond the modal when utilizing Bootstrap 3

Having an issue loading a modal with Angular and populating it with a template. The main problem I'm facing is that the inputs are extending beyond the boundaries of the modal - attached below is a screenshot illustrating the problem: Below is the c ...

Using jQuery to send a post request to a PHP script using either JavaScript or PHP

Just a quick question for those with experience. I am working on a page where I have implemented a jQuery AJAX post to another PHP page that contains JavaScript. My concern is, will the JavaScript code also be executed? Another scenario to consider is if ...

What are the steps to successfully host a socket.io server and an HTTP server simultaneously?

I have a situation where I have both a Socket.io server and a basic HTTP server that are working together, but the issue is that the HTTP server is trying to handle requests that should actually be handled by the Socket.io server. Below is the code snippe ...

What is the best way to achieve a full width table in an HTML format on a smartphone browser?

Apologies for my limited English proficiency. I am currently working on creating a horizontal scrollable table in HTML. My goal is to make the width of the table span beyond the browser's viewing area, so that sticky cell functionality can be implem ...

"Utilize Ajax to load PHP content and dynamically refresh a specific div

I have implemented an image uploading system, but now I want to incorporate a feature that allows users to rotate the uploaded images using Ajax. The challenge I'm facing is that if the session variable is lost during a full page update, I need to ens ...

Guide on using Fetch API to send a request to a PHP file using the POST method

Hey everyone, I've recently started delving into the world of PHP and I encountered an issue while attempting to send a post request from my JavaScript file to my PHP file using the Fetch API. Upon making the request in my console, I received the foll ...

Using Typescript to Declare Function and React Component Types

Currently challenging myself to delve into Typescript (ugh). Usually, I can deduce the appropriate type by analyzing the return values. Nonetheless, in this particular scenario, that method is proving ineffective. type SomeReactAProps = { Type1: ReactEle ...

Modifying the Vue.js Vue3-slider component for custom color schemes

Currently, I am using the vue-slider component and would like to customize the color of the slider itself. The specific class that needs to be styled is "vue-slider-dot-tooltip-inner". Below is a screenshot displaying the original CSS styling for vue-slid ...

Incorporate a linked select dropdown into the registration form

I am working on a sign-up form and trying to integrate 2 linked select boxes into the form. The code for the linked select boxes works fine separately but when I attempt to add it to the form, it doesn't display as expected. I attempted to incorporate ...

Sending a link via email using Node.js and Express can be achieved by integrating nodemailer into

I need help with sending clickable links via email. Below is the code I am using: const data = { from: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdd0d8fdcedcd0cdd1d8ce93d0dcd4d1dac8d393d2cfda">[email protec ...

Handling exceptions in AngularJS router-ui resolve functionality

In my app, I have the parent route listed below: .state('app',{ url: '/app', templateUrl: 'views/app.html', resolve: loadSequence('modernizr','moment'), ...

Exploring the Node environment setup within Nest.js

Currently, I am in the midst of setting up a Nest.js project and seeking an efficient solution for defining the Node environment used by the ConfigService to load environment variables: import { Module } from '@nestjs/common'; import { ConfigSer ...

Using PHP in combination with Ajax for automatically performing an action when there is an update

My goal is to have the latest value entered in the database trigger the playing of a specific song. For instance, if someone on the other side of the world selects a song on their phone, that same song should automatically start playing on all devices with ...

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

The NPM version needs to be updated as it is outdated

Struggling with a dilemma here. My Laravel project is quite dated, and I'm unable to execute npm run dev. Let's take a look at some code: php artisan laravel --version: Laravel Framework 5.8.38 node --version: v16.16.0 This is the current Node v ...