Building a Basic Node.js Project

MinhTDAbout 2 minGuideNodeJS

First, make sure you have Node.js installed on your machine. Then follow these steps to create the project:

Create a new directory for your project:

mkdir nodejs-login-todolist
cd nodejs-login-todolist

Initialize a new Node.js project:

npm init -y

Install necessary dependencies:

npm install express body-parser express-session

Create a file named app.js:

// app.js
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');

const app = express();

// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
    secret: 'secret-key',
    resave: false,
    saveUninitialized: true
}));

// In-memory storage for demonstration purpose
let users = [
    { username: 'user1', password: 'password1' },
    { username: 'user2', password: 'password2' }
];
let todos = [];

// Middleware to check if user is authenticated
const isAuthenticated = (req, res, next) => {
    if (req.session.user) {
        next();
    } else {
        res.redirect('/login');
    }
};

// Routes
app.get('/', isAuthenticated, (req, res) => {
    res.send('Welcome to Todo List App');
});

app.get('/login', (req, res) => {
    res.send(`
        <form action="/login" method="post">
            <input type="text" name="username" placeholder="Username"><br>
            <input type="password" name="password" placeholder="Password"><br>
            <button type="submit">Login</button>
        </form>
    `);
});

app.post('/login', (req, res) => {
    const { username, password } = req.body;
    const user = users.find(u => u.username === username && u.password === password);
    if (user) {
        req.session.user = user;
        res.redirect('/');
    } else {
        res.send('Invalid username or password');
    }
});

app.get('/logout', (req, res) => {
    req.session.destroy(err => {
        if (err) {
            console.error(err);
        } else {
            res.redirect('/login');
        }
    });
});

app.get('/todo', isAuthenticated, (req, res) => {
    res.send(`
        <form action="/todo" method="post">
            <input type="text" name="task" placeholder="Enter your task">
            <button type="submit">Add</button>
        </form>
        <ul>
            ${todos.map(todo => `<li>${todo}</li>`).join('')}
        </ul>
        <a href="/logout">Logout</a>
    `);
});

app.post('/todo', isAuthenticated, (req, res) => {
    const task = req.body.task;
    todos.push(task);
    res.redirect('/todo');
});

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Run the application:

node app.js

Now you can open your browser and navigate to http://localhost:3000/login to access the login page. You can use the credentials from the users array defined in the code to login. After logging in, you will be redirected to the todo list page (http://localhost:3000/todo) where you can add tasks. You can also logout by clicking the Logout link.