// Import required modules
const express = require('express');
const app = express();
const basicAuth = require('express-basic-auth');
// Define a user for basic authentication
const users = { 'username': 'password' };
// Use express-basic-auth middleware for authentication
app.use(basicAuth({ users }));
// Define a route accessible only to authenticated users
app.get('/secure', (req, res) => {
res.send('Authenticated route');
});
code
Basic Authentication using 'express-basic-auth' middleware
This Express.js code sets up basic authentication using the 'express-basic-auth' middleware. It defines a route ('/secure') that can only be accessed by authenticated users. The comments provide explanations for each part of the code.
basic authentication
Node.js
Express.js
express-basic-auth