使用Node.js和Express可快速构建RESTful API,通过HTTP方法对资源进行CRUD操作,需合理设计路由、处理JSON数据、校验输入并返回标准状态码以确保接口规范。

开发 JavaScript RESTful 服务,通常是指使用 Node.js 搭配 Express 框架来创建基于 HTTP 协议的 API 接口。这类服务遵循 REST 架构风格,通过标准的 HTTP 方法(GET、POST、PUT、DELETE 等)对资源进行操作,广泛应用于前后端分离项目中。
要开始开发 RESTful 服务,先准备好运行环境:
创建一个入口文件,例如 server.js,编写最简单的服务器启动代码:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send({ message: 'Hello from REST API' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
RESTful 的核心是“资源”,每个 URL 代表一种资源。比如用户资源可以用 /users 表示,通过不同 HTTP 方法实现 CRUD 操作:
立即学习“Java免费学习笔记(深入)”;
在 Express 中实现这些路由:
// 模拟数据
let users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
];
// 获取所有用户
app.get('/users', (req, res) => {
res.json(users);
});
// 获取单个用户
app.get('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
// 创建用户
app.post('/users', express.json(), (req, res) => {
const { name, age } = req.body;
const newUser = { id: users.length + 1, name, age };
users.push(newUser);
res.status(201).json(newUser);
});
// 更新用户
app.put('/users/:id', express.json(), (req, res) => {
const id = parseInt(req.params.id);
const user = users.find((u, i) => {
if (u.id === id) {
const index = users.indexOf(u);
users[index] = { ...u, ...req.body };
return true;
}
return false;
});
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
// 删除用户
app.delete('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
const index = users.findIndex(u => u.id === id);
if (index === -1) return res.status(404).json({ error: 'User not found' });
users.splice(index, 1);
res.status(204).send();
});
确保服务能正确解析 JSON 请求体,需使用中间件:
app.use(express.json());
返回响应时统一使用 res.json() 发送 JSON 数据,并根据情况设置状态码(如 200、201、404、500),让客户端更清楚请求结果。
真实项目中需要对输入数据做校验。例如创建用户时检查 name 是否存在:
app.post('/users', express.json(), (req, res) => {
const { name, age } = req.body;
if (!name || typeof name !== 'string') {
return res.status(400).json({ error: 'Valid name is required' });
}
const newUser = { id: users.length + 1, name, age: age || null };
users.push(newUser);
res.status(201).json(newUser);
});
可以定义全局错误处理中间件捕获未预期异常:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
以上就是JavaScript RESTful服务开发的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号