哪里有制作网站服务免费seo快速排名系统
Node.js简单接口实现教程
1. 准备工作
确保您的计算机已安装:
- Node.js (建议版本16.x以上)
- npm (Node包管理器)
2. 项目初始化
# 创建项目目录
mkdir nodejs-api-tutorial
cd nodejs-api-tutorial# 初始化npm项目
npm init -y# 安装必要依赖
npm install express body-parser
3. 项目结构
nodejs-api-tutorial/
│
├── server.js # 主服务器文件
├── package.json # 项目依赖配置
└── routes/ # 路由目录└── userRoutes.js # 用户相关路由
4. 代码实现
server.js
const express = require('express');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/userRoutes');const app = express();
const PORT = process.env.PORT || 3000;// 中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));// 注册路由
app.use('/api/users', userRoutes);// 全局错误处理中间件
app.use((err, req, res, next) => {console.error(err.stack);res.status(500).json({status: 'error',message: '服务器发生错误'});
});// 启动服务器
app.listen(PORT, () => {console.log(`服务器运行在 http://localhost:${PORT}`);
});
routes/userRoutes.js
const express = require('express');
const router = express.Router();// 模拟数据库
let users = [{ id: 1, name: '张三', age: 25 },{ id: 2, name: '李四', age: 30 }
];// 获取所有用户
router.get('/', (req, res) => {res.json(users);
});// 根据ID获取用户
router.get('/:id', (req, res) => {const user = users.find(u => u.id === parseInt(req.params.id));if (!user) return res.status(404).json({ message: '用户未找到' });res.json(user);
});// 创建新用户
router.post('/', (req, res) => {const newUser = {id: users.length + 1,name: req.body.name,age: req.body.age};users.push(newUser);res.status(201).json(newUser);
});// 更新用户
router.put('/:id', (req, res) => {const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));if (userIndex === -1) return res.status(404).json({ message: '用户未找到' });users[userIndex] = {...users[userIndex],...req.body};res.json(users[userIndex]);
});// 删除用户
router.delete('/:id', (req, res) => {const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));if (userIndex === -1) return res.status(404).json({ message: '用户未找到' });users.splice(userIndex, 1);res.status(204).send();
});module.exports = router;
5. 运行项目
# 启动服务器
node server.js# 使用Postman或curl测试接口
# GET: http://localhost:3000/api/users
# POST: http://localhost:3000/api/users (发送JSON数据)
# PUT: http://localhost:3000/api/users/1 (发送更新数据)
# DELETE: http://localhost:3000/api/users/1
6. 接口测试示例
Curl测试命令
# 获取所有用户
curl http://localhost:3000/api/users# 创建用户
curl -X POST http://localhost:3000/api/users \-H "Content-Type: application/json" \-d '{"name":"王五","age":28}'# 更新用户
curl -X PUT http://localhost:3000/api/users/1 \-H "Content-Type: application/json" \-d '{"age":26}'# 删除用户
curl -X DELETE http://localhost:3000/api/users/1
注意事项
- 这是一个使用内存数据的示例,实际生产环境应使用数据库
- 添加更多的输入验证和错误处理
- 考虑使用JWT进行身份认证
- 生产环境需要添加安全中间件和错误日志