Node.js RESTful API
在这个教程中,我们将学习如何使用 node.js 和 Express 框架来创建一个简单的 RESTful API。REST(Representational State Transfer)是一种网络应用程序的设计风格和开发方式,它基于 HTTP 协议,可以使用 XML 或者 JSON 格式传输数据。
第一步:初始化项目
创建一个新的项目目录:
mkdir my-rest-api cd my-rest-api
初始化 Node.js 项目:
npm init -y
安装 Express 和其他必要的依赖:
npm install express body-parser cors
第二步:创建服务器文件
在项目目录中创建一个名为 server.js
的文件,并添加以下代码:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;
// 中间件
app.use(bodyParser.json());
app.use(cors());
// 测试路由
app.get('/', (req, res) => {
res.json({ message: 'Welcome to the REST API!' });
});
// 启动服务器
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
第三步:创建基本的 CRUD 路由
接下来,我们将创建一个简单的用户管理 API,包括创建(Create)、读取(Read)、更新(update)和删除(Delete)操作。
创建一个
data
文件来模拟数据库: 在项目目录中创建一个名为data.js
的文件,并添加以下代码:let users = []; const addUser = (user) => { users.push(user); }; const getUserById = (id) => { return users.find(user => user.id === id); }; const updateUserById = (id, updatedUser) => { const user = getUserById(id); if (user) { const index = users.indexOf(user); users[index] = { ...user, ...updatedUser }; return true; } return false; }; const deleteUserById = (id) => { const index = users.findIndex(user => user.id === id); if (index !== -1) { users.splice(index, 1); return true; } return false; }; const getAllUsers = () => { return users; }; module.exports = { addUser, getUserById, updateUserById, deleteUserById, getAllUsers };
更新
server.js
文件以添加 CRUD 路由:const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const { addUser, getUserById, updateUserById, deleteUserById, getAllUsers } = require('./data'); const app = express(); const PORT = process.env.PORT || 3000; // 中间件 app.use(bodyParser.json()); app.use(cors()); // 测试路由 app.get('/', (req, res) => { res.json({ message: 'Welcome to the REST API!' }); }); // 用户路由 // 创建用户 app.post('/users', (req, res) => { const { name, email } = req.body; const user = { id: Date.now(), name, email }; addUser(user); res.status(201).json(user); }); // 获取所有用户 app.get('/users', (req, res) => { res.json(getAllUsers()); }); // 获取单个用户 app.get('/users/:id', (req, res) => { const user = getUserById(parseInt(req.params.id)); if (user) { res.json(user); } else { res.status(404).json({ message: 'User not found' }); } }); // 更新用户 app.put('/users/:id', (req, res) => { const { name, email } = req.body; const updated = updateUserById(parseInt(req.params.id), { name, email }); if (updated) { res.json({ message: 'User updated successfully' }); } else { res.status(404).json({ message: 'User not found' }); } }); // 删除用户 app.delete('/users/:id', (req, res) => { const deleted = deleteUserById(parseInt(req.params.id)); if (deleted) { res.json({ message: 'User deleted successfully' }); } else { res.status(404).json({ message: 'User not found' }); } }); // 启动服务器 app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
第四步:测试 API
启动服务器:
node server.js
现在,你可以使用工具如 Postman 或 curl 来测试你的 API。以下是一些测试请求的示例:
创建用户:
curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com"}' http://localhost:3000/users
获取所有用户:
curl http://localhost:3000/users
获取单个用户:
curl http://localhost:3000/users/1627890123456
更新用户:
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Jane Doe", "email": "jane@example.com"}' http://localhost:3000/users/1627890123456
删除用户:
curl -X DELETE http://localhost:3000/users/1627890123456
总结
通过这篇教程,你已经学会了如何使用 Node.js 和 Express 框架来创建一个基本的 RESTful API。你可以根据需要扩展这个示例,添加更多的功能和更复杂的逻辑。祝你编码愉快!
本文地址:https://www.tides.cn/p_node-restful-api