Attempting to leverage the combination of Express and Redis to create a secure login webpage

For my university project, I am working on creating a basic login page. The challenge that I am facing is related to using Redis as the database for storing user credentials. Despite having a running Docker with the Redis image and establishing successful connections, I am finding it difficult to retrieve values from the Redis response.

In the code snippet provided below, I am attempting to toggle a boolean value from true to false based on the data associated with a specific key ('a'). However, no matter what adjustments I make, the value remains unchanged. It's important to note that I have limited experience in JavaScript and handling asynchronous functions in Redis API.


app.get('/enter', (req, res) => {
  var username = req.query.user;
  var password = req.query.pass;
  ans = false
  redis.get(username,function(err, reply) {
    if(reply != null ) ans = true;
  })
  console.log(ans);
})

I'm simply trying to check if the key holds a value by testing variables before and after the request, yet the outcome doesn't reflect any changes made. Thank you for your assistance in this matter.

Answer №1

It appears that you may be unfamiliar with the fundamental concepts of callbacks and asynchronous behavior in JavaScript.

Here is an example of how you can structure your code:

app.get('/enter', async (req, res) => {
  var username =req.query.user;
  var password = req.query.pass;
  ans = false
  let reply = await getUsername(username)
  console.log(reply)
  console.log(ans);
})

function getUsername(username) {
   return new Promise((res, rej) => {
      redis.get(username, function(err, reply) {
         if(err) rej(err)
         res(reply)
      })
   })
}

You can simplify your redis code by using new Promise to promisify it, allowing you to utilize the async / await syntax.

Otherwise, you will have to handle your code within callbacks, which can lead to callback hell if your codebase grows.

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

A guide to testing redux API using Node.js

I'm diving into the world of nodejs and redux as a beginner. I managed to install node v7.10 on my computer. While reading through the Redux documentation, it mentioned that I should be able to test the action, reducer, and store API without a user in ...

Getting two responses using onReadyStateChange with XMLHttpRequest

What is the current situation? On my profile page, a POST request is made to the server when it loads to fetch the user's profile data. This data is then displayed in input fields for the user to edit. There is also a button at the bottom that sends ...

Automatically execute JavaScript upon loading the page with the option to value run on

Upon loading the page, Week 1 is automatically selected which is great. However, the javascript function only runs when I manually choose an option. I want the javascript to automatically trigger for week 1 without needing manual selection. Any ideas on ...

Refresh the content of a webpage in AngularJS without the need to fully reload the entire page

Within my controller and view files, I have content that is sourced from various places, including API calls. For instance, I have information retrieved from the database where users can update certain details like their last name. After submitting the up ...

Generating two fetch requests that run independently

Once we have populated a dropdown menu with fields from a fetch request, the next step is to select one of those fields and trigger another fetch request to retrieve data associated with the selected field. However, we encountered an issue where the secon ...

Ways to modify the hue of an li element in the context menu upon hovering

I'm currently working on a project that involves VueJS and Bootstrap. To enhance user experience, I've incorporated a context menu using the npm package called vue-context Vue Context Menu When a user hovers over an item on the context menu, the ...

Experiencing unexpected outcomes via AJAX requests

Linked to: Query Database with Javascript and PHP This inquiry is connected to my previous question. I made adjustments to the PHP script based on one of the responses I received; however, when attempting to utilize $.getJSON, I encountered difficulties. ...

Is there a way to retrieve information from a different object?

Access the code on Plunker I am working with two data structures - ingredients and recipes [{ "id":"1", "name": "Cucumber" }, .. ] and [{ "id":"1", "name": "Salad1", "recipein":[1, 3, 5] }, { ... } ] My goal is to ...

Challenges with UV wrapping in THREE.js ShaderMaterial when using SphereBufferGeometry

Currently, I am attempting to envelop a SphereBufferGeometry with a ShaderMaterial that incorporates noise to mimic the surface of Jupiter. However, the wrapping on the sphere geometry is turning out peculiarly. Instead of wrapping around the 'planet& ...

When the Escape key is pressed on the modal, it activates the escape event on the parent component

Welcome to the main page. "use client"; import React, { useEffect, useState } from "react"; import TestModal from "./TestModal"; const App = () => { const [isOpen, setIsOpen] = useState(false); const [isDiscardModalOp ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

Embed the website onto a webpage using ajax or an iframe without any need for navigation

I have a unique challenge ahead. Imagine there are two websites, one is a web page and the other is hosted within the same domain. My goal is to load the entire second website into a div or iframe of the first web page, similar to how a free proxy browser ...

Utilizing ng-bind-html to establish Angular bindings within the HTML code

My scenario involves hitting a specific route (#/abc) and then making a POST request to the server to render the HTML received as a response. Instead of embedding this logic directly into $routeProvider.when, I came up with my own solution. This is how I ...

Guidelines for naming classes in scss when working with Next.js

Is it possible to use CSS naming conventions in SCSS files with Next.js and then import them into JavaScript using a different convention? // login.module.scss file: .login-button { // some scss styling } // Login.js file: import styles from './ ...

Techniques for dynamically counting rows in a table using JavaScript

I'm working on a system to create and delete rows, and I want each row to have a unique row number displayed under "Num." However, I'm having trouble implementing this feature. EDIT I found a jQuery snippet that counts the first row but not t ...

spill the elements from one div into another div

I'm facing a situation where I have 2 divs on a page, with the first div containing text content only. The issue is that when the content of the first div overflows, it gets cut off due to the CSS applied to it: .one { overflow: hidden; width: 1 ...

Update or overwhelm a node_module file reference

Let's say I have an installed node_module called magicalModule, which was installed using the command npm i magicalModule. To use it in my code, I import it like this: const magic = require('magicalModule'). Now, is there a way for me to o ...

Three.js - Intense shadow cast on mesh's facial features

I have designed a chest model using blender, hand-painted a texture for it, and placed it in an environment rendered with Three.js. However, I am facing an issue with an unusually extreme shadow on the front face of the chest: Here is my setup for the Ren ...

Adding an element and updating its innerHTML can be achieved without relying on jQuery. Let's look at how this can be

I have a specific script that currently presents a list in alphabetical order. The list includes items like Apple, Banana, Blackberry, Blueberry, Cherry, and Cranberry. However, I would like to reorganize this extensive list, which consists of nearly 100 i ...

Using JavaScript to bring in npm packages

My understanding of javascript modules is still lacking. I recently embarked on a new project that required a library from npm. https://www.npmjs.com/package/random-color-pair After running npm i random-color-pair This created a "node modules" folder wh ...