构建简单的待办事项应用
开发
构建一个简单的待办事项应用程序
在这篇文章中,我们将一起创建一个简单的待办事项(To-Do List)应用。这个应用由后端(使用Node.js和Express)和前端(使用HTML和JavaScript)组成。我们的目标是使应用具有添加、显示和删除待办事项的基本功能。
步骤 1: 设置后端环境
首先,需要在计算机上安装Node.js和npm(Node包管理器)。然后在项目目录中初始化一个新的Node.js项目:
mkdir todo-app
cd todo-app
npm init -y
接着,安装Express框架:
npm install express
步骤 2: 创建后端服务器
在项目目录中创建一个server.js
文件,用于设置HTTP服务器:
const express = require('express');
const app = express();
app.use(express.json());
let todos = [];
// Endpoint 获取所有待办事项
app.get('/todos', (req, res) => {
res.json(todos);
});
// Endpoint 添加待办事项
app.post('/todos', (req, res) => {
const todo = {
id: Date.now(), // 使用时间戳作为ID
text: req.body.text,
};
todos.push(todo);
res.status(201).json(todo);
});
// Endpoint 删除待办事项
app.delete('/todos/:id', (req, res) => {
todos = todos.filter(todo => todo.id !== parseInt(req.params.id));
res.status(204).send();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
步骤 3: 创建前端界面
在项目目录下创建一个public
文件夹,并在其中创建一个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</title>
</head>
<body>
<h1>To-Do List</h1>
<input type="text" id="new-todo" placeholder="Add a new to-do">
<button onclick="addTodo()">Add</button>
<ul id="todo-list"></ul>
<script>
async function fetchTodos() {
const response = await fetch('/todos');
const todos = await response.json();
const todoList = document.getElementById('todo-list');
todoList.innerHTML = '';
todos.forEach(todo => {
const li = document.createElement('li');
li.textContent = todo.text;
const button = document.createElement('button');
button.textContent = 'Delete';
button.onclick = () => deleteTodo(todo.id);
li.appendChild(button);
todoList.appendChild(li);
});
}
async function addTodo() {
const textInput = document.getElementById('new-todo');
const text = textInput.value;
if (text) {
await fetch('/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
});
textInput.value = '';
fetchTodos();
}
}
async function deleteTodo(id) {
await fetch(`/todos/${id}`, { method: 'DELETE' });
fetchTodos();
}
// 初始加载时获取todo列表
fetchTodos();
</script>
</body>
</html>
步骤 4: 运行应用
在server.js
中,将静态文件夹设置为public
:
app.use(express.static('public'));
在命令行中,运行以下命令启动服务器:
node server.js
在浏览器中访问http://localhost:3000
,就可以看到我们的待办事项应用界面了。
总结
我们创建了一个简单的待办事项应用程序,展示了使用Node.js和Express构建API后端的基本方法,并通过一个简单的前端界面与其交互。通过这些步骤,你可以继续扩展功能,比如添加用户认证、数据持久化等来增强应用的功能。希望这篇文章对你学习全栈开发有所帮助!
编辑:一起学习网