No data entries found in the array

I've encountered an issue where after clicking the login button, the data rows section is coming back empty:

[nodemon] restarting due to changes... [nodemon] starting node server.js Example app listening on port 8080 Connected to database

{ username: 'torontofam', password: 'password' }
    result{
    command: 'SELECT',
      rowCount: 0,
      oid: null,
      rows: [],
      fields: [
        Field {
          name: 'id',
          tableID: 19247,
          columnID: 1,
          dataTypeID: 23,
          dataTypeSize: 4,
          dataTypeModifier: -1,
          format: 'text'
        },
        Field {
          name: 'username',
          tableID: 19247,
          columnID: 2,
          dataTypeID: 1043,
          dataTypeSize: -1,
          dataTypeModifier: 259,
          format: 'text'
        },
        Field {
          name: 'password',
          tableID: 19247,
          columnID: 3,
          dataTypeID: 1043,
          dataTypeSize: -1,
          dataTypeModifier: 259,
          format: 'text'
        },
    }

When executing the query in psql, this is what is returned:

    midterm=# SELECT * FROM users WHERE username = 'torontofam' AND password = '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.';;
 id |  username  |                           password                           |  latitude  |  longitude  
----+------------+--------------------------------------------------------------+------------+-------------
  1 | torontofam | $2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u. | 43.6523736 | -79.3857858
(1 row)

This is the actual query sent to the DB:

router.post("/login", (req, res) => {
const { username, password } = req.body;
console.log(req.body);
const queryString = `SELECT * FROM users WHERE username = $1 AND password = $2;`;
db.query(queryString, [username, password])
  .then((data) => {
    console.log(data);
    const user = data.rows[0];

    if (!user) {
      return res
        .status(400)
        .send({ message: "Username not found in database" });
    }

    const validPassword = bcrypt.compareSync(password, user.password);

    if (!validPassword) {
      return res
        .status(400)
        .send({ message: "Password does not match username" });
    }
    req.session.user_id = user.id;
    res.redirect("/");
  })
  .catch((err) => {
    res.status(500).json({ error: err.message });
  });

});

I'm puzzled as to why the login request keeps returning : POST /api/users/login 400 26.831 ms - 44 {"message":"Username not found in database"}

Answer №1

After some thorough troubleshooting, I was able to identify the root cause of why the data.rows were returning an empty array.

The main issue stemmed from this part of the code:

const query = `SELECT * FROM users WHERE username = $1 AND password = $2;`;
db.query(query, [username, password])

I realized that there was no need to select the password in order to retrieve the row, as the username alone should suffice.

To rectify this, I made the following adjustment to the code:

const query = `SELECT * FROM users WHERE username = $1;`;
db.query(query, [username])

Now, the updated code is producing the expected output:

{ username: 'torontofam', password: 'password' }
{
  id: 1,
  username: 'torontofam',
  password: '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.',
  latitude: 43.6523736,
  longitude: -79.3857858
}

Answer №2

Does this code pertain to MySQL? Consider substituting question marks(?) for both $1 and $2.

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

Launching Bootstrap 5 Modal Automatically when the Page Loads

I'm currently working on setting up an automatic modal that pops up when the page loads for a school project. I've been using Bootstrap 5, but most of the examples I found online are based on older versions. The specific modal I'm referring ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

What is the best way to transfer the value of one directive attribute to another directive in AngularJS?

For instance: <custom-main> <custom-sub1 att-name="test"></custom-sub1> <custom-sub2></custom-sub2> </custom-main> JavaScript Source Code bosAppModule.directive('custom-main',[&apos ...

Unable to run EJS script inside ajax 'success' function

I am facing an issue with my EJS page that utilizes AJAX to retrieve data. After loading the data, I intend to add specific content to a div. Within the added content, there are checkboxes controlled by the following script: <script> $('#select ...

Storing POST Request Data in Express

I want to use a single API endpoint for both GET and POST requests. My goal is as follows: Send multiple POST requests to /api/users with data like: {'id': 2, is_valid: 'true'} Retrieve this data by fetching the same API URL later on ...

Disregard the significance of radio buttons - iCheck

I have been attempting to retrieve values from radio buttons (using iCheck), but I am consistently only getting the value from the first radio button, while ignoring the rest. Despite following what seems to be correct code theory, the output is not as exp ...

There are four potential types for the query variable

My node server is suggesting four possible types of query when using Typescript: string | QueryString.ParsedQs | string[] | QueryString.ParsedQs[] I am looking for a way to bypass these suggestions. While I know it's possible to ignore or parse thes ...

``Change the color of the sections in a 3D pie chart on a Highcharts

I am looking to create a custom pie chart with two different colors: one for the main surface and another for the sides. Currently, I can only configure the lighter blue color for the main surface, but I would like to also change the darker blue color for ...

Conceal the div if it remains unhidden within the following 10 seconds

This piece of code is designed to show a loader image until the page finishes loading. Here is the code snippet: document.onreadystatechange = function () { var state = document.readyState if (state == 'interactive') { $('#unti ...

Is it acceptable to utilize res.send() within a trycatch block?

While utilizing a node route and incorporating a trycatch block, I am encountering an issue where Node.js is not handling it properly. In the event of an error within the code that triggers the catch block, the process fails. try { ... res.send({ messag ...

How can I configure my React frontend application to redirect based on data retrieved from an external API call?

Currently working on a small project and integrating Paystack as the Payment Processor. Whenever a user initiates a payment, Paystack provides a unique link for that specific transaction. All the necessary requests to the payment processor are implemented ...

Send error messages directly to the client side or retrieve status codes and messages

When responding to an AJAX request, encountering an app error like data validation failure can be tricky. How can we effectively communicate this to the user? 1. Returning a Status Code and Fetching Message with JS $.ajax(options).done(function(response) ...

Retrieve every item in a JSON file based on a specific key and combine them into a fresh array

I have a JSON file containing contact information which I am retrieving using a service and the following function. My goal is to create a new array called 'contactList' that combines first names and last names from the contacts, adding an &apos ...

What would be the ideal value for COOKIE_SECRET_CURRENT in the upcoming firebase-auth version?

I am currently exploring the capabilities of the next-firebase-auth package for implementing authentication in my next.js application. Before diving deep into it, I wanted to run the example provided. However, I couldn't find clear explanations regard ...

Javascript function for downloading files compatible with multiple browsers

When working with a json response on the client side to build content for an html table, I encountered an issue with saving the file to the local disk upon clicking a download button. The csvContent is generated dynamically from the json response. Here&ap ...

Managing two variables in C# Controller and View

I am facing an issue with the two variables in my controller class. The first variable, currentUserId, is supposed to store the user currently logged into the website. The second variable, currentRoomId, should track the chat room the user is in. The probl ...

How to Insert JSON into React Component's Attribute?

I am struggling with setting the value of a React component using JSON in the attribute. I want to concatenate a letter or word, but it doesn't seem to work. Is there a correct way to combine strings within a Component's attribute? In this case, ...

Learn how to capture complete stack traces for errors when using Google Cloud Functions

In the codebase I am currently working on, I came across a backend service that I would like to utilize for logging all errors along with their corresponding Http statuses. If possible, I also want to retrieve the full stack trace of these errors from this ...

Retrieve information from the index resource using AJAX

I feel like I might be overcomplicating things, but basically, I'm trying to retrieve all the data from an index resource and have it load when a button is clicked using AJAX. I've been using a serializer to tidy up the JSON. Both "/categories" ...

Transfer data from HTML button to Javascript function

I'm having trouble passing a value from a button in my HTML document to a JavaScript function in another document. I've tried using getElementById(), but it's not working. What could be the issue? Any help would be greatly appreciated. Thank ...