Lab Title: Creating a User Login System with Node.
js
Objective:
To create a Node.js application that handles basic user login functionality and demonstrates
server-side routing.
Step 2: Create a Project Folder same as created in the first program with different
name
Step 3: Initialize a Node.js Project
Step 4: Install Required Packages
1. Install Express.js, a web framework for Node.js:
Step 5: Create the Application Files
1. Create a new file named app.js in the project folder.
Step 6: Write the Code in app.js
// Import required modules
const express = require('express');
const bodyParser = require('body-parser');
// Initialize the app
const app = express();
// Middleware for parsing request bodies
app.use(bodyParser.urlencoded({ extended: true }));
// Serve the Login Page
app.get('/', (req, res) => {
res.send(`
<h1>User Login</h1>
<form action="/login" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
`);
});
// Handle Login Requests
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Dummy credentials for simplicity
const dummyUser = {
username: 'admin',
password: '12345'
};
if (username === dummyUser.username && password === dummyUser.password) {
res.send(`<h2>Welcome, ${username}!</h2>`);
} else {
res.send('<h2>Invalid username or password. Please try again.</h2>');
}
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Step 7: Run the Application
1. Open the terminal in the project folder.
The terminal will display:
Step 8: Test the Application
1. Open a web browser and go to http://localhost:3000/.
2. Enter the following dummy credentials:
o Username: admin
o Password: 12345
3. Click Login:
o If the credentials are correct, you will see a welcome message.
o If the credentials are incorrect, you will see an error message.