Prompting a 401 error immediately after attempting to login through the Express REST API

Recently, I've encountered a strange issue with the controller for my login route. It was working perfectly fine yesterday without any hiccups, but suddenly it stopped functioning properly. Despite not making any changes to the code, it now consistently falls through to the catch block and throws an error. Strangely enough, there is no actual error being logged, leaving me uncertain about how to proceed.

This snippet shows my app.js file:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const systemRoutes = require('./routes/system');
const recipeRoutes = require('./routes/recipes');
const authRoutes = require('./routes/auth');

const app = express();


app.use(bodyParser.json());

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*'); // Will restrict later
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});


app.use('/api/system', systemRoutes);
app.use('/api/feed', recipeRoutes);
app.use('/api/auth', authRoutes);


// TODO: Implement error handling and validation


mongoose.connect('mongodb://localhost:27017/learn')
    .then(result => {
        app.listen(8080);
    })
    .catch(err => {
        console.error(err);
    });

And here's the relevant part of my controller logic:

exports.login = (req, res, next) => {
    let fetchedUser;
    User.findOne({ username: req.body.username })
        .then(user => {
            if (!user) {
                return res.status(401).json({
                    message: 'Authentication failed'
                });
            }

            fetchedUser = user;
            return bcrypt.compare(req.body.password, user.password);
        })
        .then(passwordMatch => {
            if (!passwordMatch) {
                return res.status(401).json({
                    message: 'Authentication failed'
                });
            }

            const token = jwt.sign(
                { username: fetchedUser.username, userId: fetchedUser._id },
                'secret_sauce',
                { expiresIn: '30d' }
            );

            res.status(200).json({
                token: token,
                userId: fetchedUser._id
            });
        })
        .catch(err => {
            return res.status(401).json({
                message: 'Error occurred during authentication',
                error: err
            });
        });
}

In addition, take a look at this screencap of the issue: https://i.sstatic.net/s6wyS.png

Answer №1

Given the limited information provided, I will offer alternative debugging suggestions:

Have you examined the contents of req.body?

Additionally, have you verified that the code is reaching the catch statement? If it did, the error object should not be empty.

To eliminate this possibility, consider revising the error messages to better identify the source of the problem. For instance, use a message like cannot find that userId when calling res.status(401).

Another recommendation is to adjust the status codes to accurately reflect the nature of the error. A forbidden status code typically indicates client-side errors, such as attempting to access a protected route without a valid token.

For example:

  if(!user) {
    res.status(404).json({
      message: 'Couldn\'t find the username provided.'
     });
    }

I trust this advice proves beneficial for your debugging process!

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

Accessing PageController through XmlHttpRequest is not allowed in Shopware 6

I'm encountering an issue when attempting to send a request to my customized StorefrontController on the most recent version of Shopware 6.2.2. The error message I'm receiving is: PageController can't be requested via XmlHttpRequest. I&apos ...

In the dragstart event handler, event.dataTransfer and event.originalEvent will consistently be null

I have been working on developing drag and drop directives for angularJS by referencing this informative post: However, I am facing an issue where the dataTransfer and originalEvent are consistently null within the dragstart event handler, preventing me f ...

Avoiding the default action to submit AJAX form data won't result in any changes to the front end?

Currently, I am working with Flask and have utilized JavaScript to prevent default behavior in order to send all the necessary data through an AJAX request. However, I am facing an issue where although my view contains all the data (verified by console out ...

Apply a Fade In transition to the ul li elements following a JavaScript toggle

I'm currently experimenting with implementing a Fade in from the right animation for the links displayed in the menu after toggling the menu body in the browser. Despite my efforts, I am unable to determine why the animation is not functioning as expe ...

A superior method for implementing CSS keyframe transitions

Currently, I am utilizing the Rico St.Cruz brilliant query.transit library for my work. However, I need to make some changes involving classes instead of CSS transitions. Although I am not very confident in CSS transitions, I attempted to replace: JS: $ ...

What is the best way to rotate an image using AngularJS?

Hey there, I've got an image that I need help rotating. There are two buttons - left and right - that should rotate the image 45 degrees in opposite directions. I attempted to create a directive using the jquery rotate library, but it's not worki ...

Issue with showing Angular directive

I've been working on implementing an angular dropdown list with Bootstrap. The functionality includes a directive that allows the user to select a menu option from the dropdown and receive an alert message. To see the implementation in action, I have ...

No element found with the specified exportAs value of "ngForm" on the <form> tag

I am currently experimenting with a template driven form in Angular, but I encountered an error stating **There is no directive with “exportAs” set to “ngForm"** I have made sure to import FormsModule and ReactiveFormsModule in app.module.ts as well ...

Ways to retrieve an input field value without triggering form submission

I'm currently working on a payment form where users input the amount in a text field. I also have another text field on the same form that should automatically display the amount in words based on the user input. However, I'm struggling to figure ...

Utilizing Vue.js to initiate a server request with vue-resource

Seeking guidance on performing a server call using vue-resource. I'm unsure about how to set the header and send data via Vue.$http.post Vue.$http.post('http://url/', { email: 'foo', password: 'bar' }, { headers: { ...

When the "ok" button is clicked in a custom confirmation box, the function will return

When the first button is clicked, I validate certain text boxes and then call Confirm() to display a confirmation box. I want it to return true to the calling function when "ok" is clicked and for control to go back to the UI to proceed ...

Issues retrieving information from a module in Express Node.js

Below is the code I have written in one file: models/exported.js module.exports = { processedList: function(store_name) { var t; var tradeIds = exported.find({storename: store_name}, function (err, value) { ...

tips for using Node Mailer to send emails without using SMTP

Currently, I am facing an issue with sending emails through nodemailer. Although I have successfully used my gmail account for this purpose in the past, I now wish to switch to using my business email to communicate with clients on a regular basis. The cu ...

Uniform Image Sizes in Bootstrap Carousel (With One Exception)

I am encountering a JavaScript exception related to image size. I am trying to set a fixed size for the images in my carousel, allowing them to auto adjust or resize without concern for distortion or pixelation. I have experimented with max-width and widt ...

The background-size:cover property fails to function properly on iPhone models 4 and 5

I have taken on the task of educating my younger sister about programming, and we collaborated on creating this project together. Nicki Minaj Website However, we encountered an issue where the background image does not fully cover the screen when using b ...

What is the best way to search for documents that have all conditions met within a sub-array entry?

My rolesandresponsibilities collection document is displayed below: [{ "_id": { "$oid": "58b6c380734d1d48176c9e69" }, "role": "Admin", "resource": [ { "id": "blog", "permissions": [ " ...

Control the start and stop of an Express.js app in Node.js using PHP

I'm currently developing a web service using express.js in the node.js npm environment. In order to deliver this project to my client, I need to create a controller file that allows me to start and stop the server without having to use the command pr ...

Utilizing JavaScript to Load and Showcase Images from a Temporary Image to imgsrc

How can I dynamically display images from the temporary image array 'tempimages' onto the 'img' element with the 'src' property? I have written a code that attempts to display temporary images from 'tempimages[]' on ...

Using JavaScript regex to match repeating subgroups

Can a regular expression capture all repeating and matching subgroups in one call? Consider a string like this: {{token id=foo1 class=foo2 attr1=foo3}} Where the number of attributes (e.g. id, class, attr1) are variable and can be any key=value pair. C ...

The Consequences of Using Undeclared Variables in JavaScript

What is the reason behind JavaScript throwing a reference error when attempting to use an undeclared variable, but allowing it to be set to a value? For example: a = 10; //creates global variable a and sets value to 10 even though it's undeclared al ...