构建简单待办事项应用程序
开发
构建一个简单的待办事项应用程序:从设计到实现
在这篇文章中,我们将构建一个简单的待办事项(To-Do List)应用程序。我们将从功能设计开始,然后进行代码实现,并逐步讲解每个步骤,以帮助您更好地理解整个过程。
功能设计
我们的待办事项应用程序需要具备以下基本功能:
- 添加一条新的待办事项。
- 显示所有待办事项列表。
- 标记待办事项为已完成。
- 删除已完成的待办事项。
技术栈
我们将使用以下技术来构建该应用程序:
- 前端:HTML, CSS, JavaScript
- 后端:Node.js, Express.js
- 数据库:内存存储(为了简单,我们不使用外部数据库)
步骤一:设置基础项目
首先,我们需要设置一个 Node.js 项目。
mkdir todo-app
cd todo-app
npm init -y
npm install express
步骤二:创建服务器
在项目根目录下创建一个文件 server.js
,用于设置我们的服务器。
const express = require('express');
const app = express();
const port = 3000;
let todoList = [];
// Middleware to parse JSON requests
app.use(express.json());
// Serve static files
app.use(express.static('public'));
// Start the server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
步骤三:实现基本的路由
我们需要实现一些基本的 API 路由来处理待办事项的数据操作。
// GET all todos
app.get('/api/todos', (req, res) => {
res.json(todoList);
});
// POST a new todo
app.post('/api/todos', (req, res) => {
const todo = { id: Date.now(), text: req.body.text, completed: false };
todoList.push(todo);
res.status(201).json(todo);
});
// PUT to update a todo as completed
app.put('/api/todos/:id', (req, res) => {
const todo = todoList.find(t => t.id === parseInt(req.params.id));
if (todo) {
todo.completed = true;
res.json(todo);
} else {
res.status(404).send('Todo not found');
}
});
// DELETE a completed todo
app.delete('/api/todos/:id', (req, res) => {
todoList = todoList.filter(t => t.id !== parseInt(req.params.id));
res.status(204).send();
});
步骤四:创建前端界面
创建一个 public
文件夹,并在其中创建 index.html
和 style.css
文件。我们将构建一个简单的用户界面来与我们的 API 交互。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List App</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<h1>To-Do List</h1>
<input type="text" id="new-todo" placeholder="Add a new task...">
<button onclick="addTodo()">Add</button>
<ul id="todo-list"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
style.css
body {
font-family: Arial, sans-serif;
}
#app {
max-width: 600px;
margin: 50px auto;
text-align: center;
}
ul {
list-style-type: none;
padding: 0;
}
li {
padding: 10px;
border-bottom: 1px solid #ccc;
}
.completed {
text-decoration: line-through;
}
步骤五:编写前端逻辑
创建一个 script.js
文件来实现前端逻辑。
script.js
document.addEventListener('DOMContentLoaded', loadTodos);
function loadTodos() {
fetch('/api/todos')
.then(response => response.json())
.then(todos => {
const todoList = document.getElementById('todo-list');
todoList.innerHTML = '';
todos.forEach(todo => {
const li = document.createElement('li');
li.textContent = todo.text;
li.className = todo.completed ? 'completed' : '';
li.onclick = () => completeTodo(todo.id);
todoList.appendChild(li);
});
});
}
function addTodo() {
const input = document.getElementById('new-todo');
const text = input.value.trim();
if (text !== '') {
fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
}).then(() => {
input.value = '';
loadTodos();
});
}
}
function completeTodo(id) {
fetch(`/api/todos/${id}`, {
method: 'PUT'
}).then(() => loadTodos());
}
结论
通过上述步骤,我们构建了一个简单的待办事项应用程序。这个应用程序展示了如何使用 Node.js 和 Express.js 设置服务器,提供 RESTful API,并通过简单的 HTML、CSS 和 JavaScript 构建前端界面。您可以继续扩展该应用程序的功能,例如添加用户身份验证或使用数据库进行持久化存储。希望这篇教程对您有所帮助!
编辑:一起学习网