一起学习网 一起学习网


构建简单的Todo应用:完整实现

开发 Todo app, Node.js, Express, 前端开发, 后端API 06-06

构建一个简单的Todo应用:从后端到前端的完整实现

在这篇文章中,我们将构建一个简单的Todo应用程序,从后端API到前端界面,实现一个完整的功能链。我们的应用将允许用户添加、查看和删除Todo任务。

第一步:后端API

我们将使用Node.js和Express来创建我们的后端API。首先,确保你安装了Node.js和npm,然后创建一个新的项目目录并初始化项目:

mkdir todo-app
cd todo-app
npm init -y

接下来,安装Express:

npm install express

创建一个文件 server.js 来设置我们的Express服务器:

const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

let todos = [];

// Get all todos
app.get('/todos', (req, res) => {
    res.json(todos);
});

// Add a new todo
app.post('/todos', (req, res) => {
    const todo = req.body;
    todos.push(todo);
    res.status(201).json(todo);
});

// Delete a todo
app.delete('/todos/:id', (req, res) => {
    const id = parseInt(req.params.id, 10);
    todos = todos.filter(todo => todo.id !== id);
    res.status(204).send();
});

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

第二步:前端界面

我们将使用HTML、CSS和JavaScript来创建前端。首先,在项目目录中创建一个文件 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Todo App</title>
    <style>
        body { font-family: Arial, sans-serif; }
        .todo-list { list-style-type: none; padding: 0; }
        .todo-item { display: flex; justify-content: space-between; }
    </style>
</head>
<body>
    <h1>Todo App</h1>
    <input type="text" id="todoInput" placeholder="Enter a new todo">
    <button onclick="addTodo()">Add Todo</button>
    <ul id="todoList" class="todo-list"></ul>

    <script src="app.js"></script>
</body>
</html>

创建 app.js 来处理前端逻辑:

const apiUrl = 'http://localhost:3000/todos';

async function fetchTodos() {
    const response = await fetch(apiUrl);
    const todos = await response.json();
    const todoList = document.getElementById('todoList');
    todoList.innerHTML = '';
    todos.forEach(todo => {
        const li = document.createElement('li');
        li.className = 'todo-item';
        li.innerHTML = `
            ${todo.text}
            <button onclick="deleteTodo(${todo.id})">Delete</button>
        `;
        todoList.appendChild(li);
    });
}

async function addTodo() {
    const todoInput = document.getElementById('todoInput');
    const todo = { id: Date.now(), text: todoInput.value };
    await fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(todo)
    });
    todoInput.value = '';
    fetchTodos();
}

async function deleteTodo(id) {
    await fetch(`${apiUrl}/${id}`, {
        method: 'DELETE'
    });
    fetchTodos();
}

fetchTodos();

第三步:运行应用

  1. 在终端中启动Node.js服务器:

    node server.js
    
  2. 打开 index.html 文件,使用浏览器查看,并进行Todo任务的添加和删除。

通过这些步骤,你已经成功创建了一个简单的Todo应用,涵盖了从后端API的实现到前端交互。该应用展示了如何使用Node.js和Express处理API请求,以及如何通过JavaScript来更新用户界面。


编辑:一起学习网