Encountering a 404 error indicating that the file cannot be found while attempting to log into an authentication system developed using express and node

Currently, I am in the process of developing a demonstration banking application that facilitates user sign up and sign in functionality using express.js and node.js. The API created accepts POST requests to /signup and /authenticate routes successfully when tested on Postman. However, an issue arises when attempting to call the /authenticate route using $.ajax from the login form.

Below is the jQuery ajax request from index.html

$.ajax({
        url: '/authenticate',
        method: 'POST',
        data: cred,
        dataType: 'json',
        processData: false,
        contentType: false,
        success: function(success){
          console.log(success);
        },
        error: function(err){
          console.log(err);
        }
      })

This snippet showcases server.js which serves as the server file

app.use(express.static(__dirname + '/../public'));

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/../public/index.html'));
});

app.use('/api', api(passport));

Additionally, here is app.js where routing is defined

'use strict';

var router = require('express').Router();

var config = require('../config'),
    allowOnly = require('../services/routesHelper').allowOnly,
    AuthController = require('../controllers/authController'),
    UserController = require('../controllers/userController',
    AdminController = require('../controllers/adminController');

var APIRoutes = function(passport) {
    // POST Routes.
    router.post('/signup', AuthController.signUp);
    router.post('/authenticate', AuthController.authenticateUser);

    // GET Routes.
    router.get('/profile', passport.authenticate('jwt', { session: false }), allowOnly(config.accessLevels.user, UserController.index));
    router.get('/admin', passport.authenticate('jwt', { session: false }), allowOnly(config.accessLevels.admin, AdminController.index));

    return router;
};

module.exports = APIRoutes;

The /signup POST request functions correctly but encounters a 404 error when accessing via Ajax. Interestingly, the /authenticate endpoint behaves as expected when accessed through Postman.

Referencing the authController.js below

var jwt = require('jsonwebtoken');

var config = require('../config'),
    db = require('../services/database'),
    User = require('../models/user');

// The authentication controller.
var AuthController = {};

// Register a user.
AuthController.signUp = function(req, res) {
    if(!req.body.username || !req.body.password) {
        res.json({ message: 'Please provide a username and a password.' });
    } else {
        db.sync().then(function() {
            var newUser = {
                username: req.body.username,
                password: req.body.password
            };

            return User.create(newUser).then(function() {
                res.status(201).json({ message: 'Account created!' });
            });
        }).catch(function(error) {
            console.log(error);
            res.status(403).json({ message: 'Username already exists!' });
        });
    }
}

// Authenticate a user.
AuthController.authenticateUser = function (req, res) {
  if (!req.body.username || !req.body.password) {
    res.status(404).json({
      message: 'Username and password are needed!'
    });
  } else {
    var username = req.body.username,
      password = req.body.password,
      potentialUser = {
        where: {
          username: username
        }
      };

    User.findOne(potentialUser).then(function (user) {
      if (!user) {
        res.status(404).json({
          message: 'Authentication failed!'
        });
      } else {
        user.comparePasswords(password, function (error, isMatch) {
          if (isMatch && !error) {
            var token = jwt.sign({
                username: user.username
              },  
              config.keys.secret, {
                expiresIn: '30m'
              }
            );

            res.json({
              success: true,
              token: 'JWT ' + token,
              role: user.role
            });
          } else {
            console.log("Log err")
            res.status(404).json({
              message: 'Login failed!'
            });
          }
        });
      }
    }).catch(function (error) {
      res.status(500).json({
        message: 'There was an error!'
      });
    })
  }
}


module.exports = AuthController;

Subsequently, a log of responses has been included for reference.

POST /api/authenticate 404 5.092 ms - 47

Executing (default): SELECT id, username, password, role, createdAt, updatedAt FROM users AS user WHERE user.username = 'sipho' LIMIT 1;

POST /api/authenticate 200 519.020 ms - 193

I have exhausted all possible strategies. Any assistance would be greatly appreciated given my limited experience with node and Express.

Answer №1

Automatically, Express responds with a 404 error when the path does not match any declared routes. However, in your scenario, it appears that the declaration is correct.

  • Check the logs to confirm that your method is being accessed

  • Implement different logging/console outputs to identify which specific 404 error is being triggered. Alternatively, return various HTTP codes in each location to pinpoint the problematic area

  • Investigate why the condition leading to the 404 response is being met and determine the root cause of the issue

For instance, if the first 404 response occurs, it may indicate that the username or password is not being sent correctly in the AJAX request. If it's the second 404, it might be due to the username not being registered or saved in the database.

I hope this explanation aids in resolving your issue

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

Issue with Webpack - npm run start and build operation not functioning?

Although I typically use create-react-app for my React projects, I decided to create one without it. However, I am encountering issues with the webpack configuration as I am not very familiar with it: This is how my package.json file looks like: { " ...

Display the bash script results on an HTML webpage

My bash script fetches device status and packet loss information, slightly adjusted for privacy: #!/bin/bash TSTAMP=$(date +'%Y-%m-%d %H:%M') device1=`ping -c 1 100.1.0.2 | grep packet | awk '{ print $6 " " $7 " " $8 }'` device2=`pin ...

How to disable the underline styling for autocomplete in a React Material UI component

Seeking assistance with removing underline styling and changing text color upon focus within the autocomplete component of React Material UI. Struggling to locate the specific style needing modification. Appreciate any help in advance! ...

The environment variables remain static within the .next directory of Next.js production

After building a full-stack app using Netxjs, I generated a build and uploaded the .next folder on Cpanel. Setting up my node app: Here is a screenshot of my node app console: https://i.stack.imgur.com/sbpIP.jpg I added environment variables in both node ...

Loop through the v-for based on the input number that was selected

I'm looking to accomplish the following: if a user selects input X (a number between 1 and 10), I want to render a specific vue component X times. It seems to work if I use v-for n in 10, but not when I use variables. <template> <div> ...

Guide on displaying several items from Laravel to Vue through the JavaScript filter method?

I need help transferring multiple objects from laravel to vue and filling my vue objects with information retrieved from the database. This is the data received from laravel: Vue objects to be populated: storeName: {}, storeUrl: {}, appName: {}, ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

Connecting an npm package with matching devDependencies and peerDependencies causes issues in app development when utilizing webpack

I am currently facing the following scenario: Frontend's package.json { "dependencies": { "lib" : "1.0.0", "foo" : "1.0.0" } } lib's package.json { "devDependencies": { ...

Creating interactive labels in a histogram that update based on the user's input

Currently, I have operational code in place that takes input data and generates a histogram based on set thresholds. When the code is executed, the histogram changes dynamically as the threshold slider is adjusted. However, there seems to be an issue wit ...

What is the best way to search for items using only a portion of a phone number or typing a name in any case (uppercase, lowercase) and still get accurate results?

let contacts = [ { name: 'John', phone: 987654 }, { name: 'Sara', phone: 654321 } ] I am developing a contact manager app with various functions to manage contacts. Add new contac ...

Modify the form's action attribute when submitted

I am trying to create a form with multiple buttons that will change the action and target properties when a specific button is clicked. Below is my code snippet: <div id="root"> <form :action="form.action" ref="form" :target="form.target"&g ...

What are the best practices for iterating through asynchronous generator functions?

Suppose we have an asynchronous generator: exports.asyncGen = async function* (items) { for (const item of items) { const result = await someAsyncFunc(item) yield result; } } Can we apply mapping to this generator? In essence, I am attempting ...

jQuery UI Drag and Drop problem with mouse positioning

I am currently working on a website that allows users to drag different "modules" (squares with information) from one location to another on the page using jQuery UI. However, I am facing an issue where when a module is dragged to a droppable zone, the sc ...

Using AJAX to send a POST request with the PHP $_FILES superglobal while preventing the default form submission with the onclick

Seeking to implement a photo upload form using an AJAX script that is currently in place. Currently, I have the html form with a file input field. Upon submission, there is an onclick event triggering "PostForm(); return false;" This action directs to a ...

What could be causing the command script for my npm package to be unique compared to the scripts for other packages?

Recently, I created my own npm package called makeTimeTable Excitedly, I installed it in cygwin using the following command: npm install -g maketimetable However, upon attempting to run the command line, I encountered an error: /node_modules/maketimeta ...

Having Trouble with Integrating Parametized URL in ExpressJS and NodeJS?

I'm currently working on implementing the delete method in Node.js. The ID of the item I want to delete must be fetched from the parameterized URL. Here is a snippet of the code: In the route: const express = require('express'); const ro ...

Discover the position of a dynamically added element

Is there a way to identify the specific dynamically added checkbox that was clicked, whether by index or name? I came across a similar question with a solution in this JSFiddle: JSFiddle Instead of just displaying "clicked", I would like it to show someth ...

Tracking Command Cooldowns in Discord.js: How to Calculate Time Remaining

Is it possible to modify the cooldown feature so that it shows the remaining time until the user can work again, rather than displaying a fixed wait time message? const { RichEmbed } = require("discord.js"); const { stripIndents } = require("common-tag ...

What is the process for dynamically looping through a table and adding form data to the table?

I am in the process of developing an hour tracking website that utilizes a form and a table. Currently, I have implemented the functionality where the form content gets added to the table upon the first submission. However, I need it to allow users to inp ...

Attempting to utilize a namespace-style import for calling or constructing purposes will result in a runtime failure

Using TypeScript 2.7.2 and VSCode version 1.21 with @types/express, I encountered an issue where in certain cases VSCode would report errors like: A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Interestingly ...