Exploring the fundamentals of authentication with Express JS

Currently, I am encountering a challenge while attempting to implement basic authentication with Username and Password using Express JS. The problem lies in the fact that when I try to incorporate an if statement within an app.use() function, it does not seem to produce any output. Below is a snippet of the code along with the result I am currently facing:

const express = require('express');
const app = express();
const basicAuth = require('express-basic-auth');

app.get('/protected', (req,res)=> {
    app.use(basicAuth({authorizer: myAuthorizer}));

    function myAuthorizer(username, password) {
        const userMatches = basicAuth.safeCompare(username, 'admin');
        const passwordMatches = basicAuth.safeCompare(password, 'admin');

        if (userMatches === 'admin' && passwordMatches === 'admin') {
            res.send("Welcome, authenticated client");
        } else {
            res.send("401 Not authorized");
        }
    }
});
app.listen(8080, ()=> console.log('Web Server Running on port 8080!'));

Upon curling to the localhost server, I receive an empty reply from the server. Refer to the image below for more information and guidance on how to troubleshoot: https://i.sstatic.net/mHkij.png

Answer №1

Perhaps taking a deep dive into the world of Middlewares could be beneficial for you. Check out this guide on using Middlewares

const express = require('express');
const app = express();
const basicAuth = require('express-basic-auth');

function myAuthorizer(username, password) {
    const userMatches = basicAuth.safeCompare(username, 'admin')
    const passwordMatches = basicAuth.safeCompare(password, 'admin')

    return userMatches && passwordMatches
}

app.use(basicAuth({ authorizer: myAuthorizer }))

app.get('/protected', (req, res) => {
    
    res.send("Welcome, authenticated client");

});

app.listen(8080, () => console.log('Web Server Running on port 8080!'));

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

Utilizing asynchronous JavaScript imports within exported classes

Currently, I have a package with async/dynamic exports that I import in the following manner: (async function() { const libEd = await import("../../.cache/ed25519wars/index.js"); })(); I plan to re-expose certain functions from libEd within a class str ...

What is the best way to create a dynamic pie chart in AngularJS using JSON data?

In my controller: When calling the web services, if the service is successful, then retrieve the data and push it into the corresponding arrays. for(var i = 0; i < $scope.reportRangeList.length; i++) { count++; if( ...

The Element Ui component fails to update when the prop of the Vue component changes

In my project, I have a parent component and several child components which all make use of the same prop. This prop is an array of keys that are used for a dropdown menu in element.js. Initially, when the children render for the first time, they do not co ...

Having difficulty rendering JSON data on an HTML webpage

Currently, I am working on an API App that utilizes the Foursquare API. With the help of my getRequest function, I am able to obtain results in JSON format, which are then displayed in my console.log. However, the challenge lies in parsing the data from J ...

Steps to retrieve the central coordinates of the displayed region on Google Maps with the Google Maps JavaScript API v3

Is there a way to retrieve the coordinates for the center of the current area being viewed on Google Maps using JavaScript and the Google Maps JavaScript API v3? Any help would be greatly appreciated. Thank you! ...

Alerts when operating with curl

$dm_post = 'DATA=' . urlencode('<?xml version="1.0" encoding="ISO-8859-1"?><REPORTE><NROCTA>1098670</NROCTA><DETALLE><CONSULTA><CLAVE>123456</CLAVE><TIPO>1</TIPO><OPERACIONES> ...

How to extract information for divs with specific attribute values using Jquery

I have multiple divs with IDs like #result-1, #result-2, each followed by a prefix number. To count the number of list items within these divs, I use the following code: $(document).ready(function () { var colorCount = $('#result-1 .item-result ...

Switching CSS styles - seeking a smoother integration

I have successfully implemented a JS CSS switcher, which works brilliantly. However, I would like it to function more seamlessly. When opening a new page on the site, the default CSS style sometimes flickers briefly before the selected CSS style is reappli ...

"Extracting JSON data from a URL and loading it into a

I am currently working on a project where I am retrieving data from a URL and storing it in an array. Here is the code snippet: $url = 'https://www.datastro.eu/api/explore/v2.1/catalog/datasets/orbits-for-current-comets-in-the-mpc-database/records?ord ...

Obtain the JSON data from the body of the current post request in Express.js

I have been working on retrieving the actual request body JSON in express.js but haven't been successful so far. Most of the resources I found online only show how to access the body of type ReqBody, whereas I am looking for a way to retrieve the actu ...

Encountering a message error for the Collapse component in Material UI

I'm currently working on creating a hamburger menu using Material UI List in Next.js, inspired by the Nested List example in the Material UI documentation. However, I've encountered an error when using "collapse" in my code. The rest of the code ...

Showing a property only as you scroll through the page

Seeking assistance on creating a scrolling effect for a box shadow property using HTML, CSS, and JS. The goal is to have the shadow appear with a subtle transition while scrolling and then disappear when scrolling stops. Here's the code I've be ...

Utilizing JavaScript to Parse RSS XML Feeds Across Domains

Looking to parse an RSS (XML) file without relying on the Google RSS feed. I have attempted using JSONP, but it resulted in downloading the file and throwing an error "Uncaught SyntaxError: Unexpected token < ". $.ajax({ type: "GET", ur ...

How can we compress videos on an Android device prior to uploading them through a web browser?

Can video compression be done prior to uploading via a web browser? For example, in iOS devices you can choose a video using the HTML input type file tag and iOS will automatically compress it before uploading. Are there any JavaScript or jQuery libraries ...

Check to see if two sets of coordinates fall within the specified radius

I'm currently working on analyzing the collision data for major intersections in my city by aggregating it with the location information. My main goal is to determine the number of accidents that occurred within a 20-meter radius of each intersection. ...

Could someone please assist me in figuring out the issue with my current three.js code that is preventing it from

Recently, I decided to delve into learning three.js and followed the getting started code on the official documentation. However, I encountered a frustrating issue where the scene refused to render, leaving me completely perplexed. Here is my index.html: ...

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

Fixing the problem of digest overflow in AngularJS

I've been working on a code to display a random number in my view, but I keep encountering the following error message: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! It seems to be related to a digest outflow issue, and I&apo ...

Creating a User Registration and Authentication System with JavaScript for a Database

I'm new to the world of web development and I've encountered a bit of a challenge. I'm looking for a Javascript framework that can handle user registration and authentication with a database, similar to what I would do with PHP and MySql. I ...

Nested loops with synchronous calls running in parallel

Is there a way to make synchronous calls in two nested 'for' loops in Node.JS? I have an Asynchronous call, but I am unsure how to modify it to work synchronously and go to the next iteration when create_db is done! var new_items = []; f ...