NodeJS Slip12B Solution

Step 1: First we create Login form for user

//form.html
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="/Slip12a.js" method="post">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit">Login</button>
</form>
</body>
</html>


Step 2: Create NodeJS page to add javascript code

//Slip_12A.js
const express = require('express');
const path = require('path');
const app = express();
const PORT = 3000;

// Middleware to parse JSON bodies
app.use(express.json());
// Middleware to parse URL-encoded bodies
app.use(express.urlencoded({ extended: true }));

// Serve the login form HTML page
app.get('/login', (req, res) => {
res.sendFile(path.resolve(__dirname, 'form.html'));
});

// In-memory user data
const users = [
{ username: 'abc', password: 'mno' },
{ username: 'mno', password: 'abc' }
];

// Login endpoint
app.post('/Slip12a.js', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password === password);
if (user) {
res.status(200).json({ message: 'Login successful', user });
} else {
res.status(401).json({ message: 'Invalid username or password' });
}
});

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

No comments:

Post a Comment