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