Implementation Steps:
1. Get Node.js on Your System
2. Create project folder and files:
- server.js
- public/register.html
- public/login.html
3. Open a terminal in your project folder
4. Initialize the project:
npm init -y
5. Install packages:
npm install express body-parser
6. Run the server:
node server.js
7. Open the browser and enter:
http://localhost:3000
8. Create:
- Register a new user
- Log in using the same credentials
That’s it, a simple flow:
Server start → Open browser → Register → Login → Output
Server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const PORT = 3000;
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
// In-memory storage
const users = {};
// Routes
// Register page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public/register.html'));
});
// Login page
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'public/login.html'));
});
// Register
app.post('/register', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.send("Please fill all fields");
}
if (users[username]) {
return res.send("User already exists");
}
users[username] = password;
res.send("Registration successful");
});
// Login
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (!users[username]) {
return res.send("User not found");
}
if (users[username] !== password) {
return res.send("Wrong password");
}
res.send("Login successful");
});
// Start server
app.listen(PORT, () => {
console.log("Server running at http://localhost:3000");
});
Register.html
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<h2>Register</h2>
<form action="/register" method="POST">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<button type="submit">Register</button>
</form>
<br>
<a href="/login">Go to Login</a>
</body>
</html>
Login.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="/login" method="POST">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<button type="submit">Login</button>
</form>
<br>
<a href="/">Go to Register</a>
</body>
</html>






0 Ravula Kartheek:
Post a Comment