开发
创建项目文件夹: 首先,创建一个新的文件夹来存放您的项目,例如todo-app。 初始化Node.js项目: 在项目文件夹中打开终端,运行以下命令来初始化一个新的Node.js项目:
安装Express: Express是一个轻量级的Node.js Web应用框架,非常适合作为后端API服务器。安装Express: 创建后端服务器: 在项目文件夹中创建一个名为server.js的文件,并添加以下代码来设置一个简单的Express服务器:const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
// 待办事项数组
let todos = [];
// 获取待办事项列表
app.get('/todos', (req, res) => {
res.json(todos);
});
// 添加待办事项
app.post('/todos', (req, res) => {
const todo = req.body;
todos.push(todo);
res.status(201).json(todo);
});
// 删除待办事项
app.delete('/todos/:id', (req, res) => {
const index = todos.findIndex(t => t.id === parseInt(req.params.id));
todos.splice(index, 1);
res.json({ message: 'Todo deleted successfully' });
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
import React, { useState, useEffect } from 'react';
function TodoList() {
const [todos, setTodos] = useState([]);
useEffect(() => {
fetch('/todos')
.then(res => res.json())
.then(data => setTodos(data));
}, []);
const handleAddTodo = todo => {
fetch('/todos', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(todo)
})
.then(res => res.json())
.then(data => setTodos([...todos, data]));
};
const handleDeleteTodo = id => {
fetch(`/todos/${id}`, {
method: 'DELETE'
}).then(() => setTodos(todos.filter(t => t.id !== id)));
};
return (
<div>
<h1>Todo List</h1>
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.text}
<button onClick={() => handleDeleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
<form>
<input type="text" placeholder="Add todo" />
<button type="submit" onClick={e => {
e.preventDefault();
handleAddTodo({ text: e.target[0].value, id: Date.now() });
}}>Add</button>
</form>
</div>
);
}
export default TodoList;