Node.js简单接口实现教程

Node.js简单接口实现教程

1. 准备工作

确保您的计算机已安装:

  • Node.js (建议版本16.x以上)
  • npm (Node包管理器)

2. 项目初始化

bash 复制代码
# 创建项目目录
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

javascript 复制代码
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

javascript 复制代码
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. 运行项目

bash 复制代码
# 启动服务器
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测试命令

bash 复制代码
# 获取所有用户
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进行身份认证
  • 生产环境需要添加安全中间件和错误日志
相关推荐
定栓40 分钟前
Webpack迁到Vite第五节:第三方库兼容
前端·webpack·node.js
G018_star sky♬6 小时前
如何用nodejs写一个简单后端服务
node.js
kiracrimson6 小时前
npm 入门:包管理器、依赖与 npx
前端·npm·node.js
花花鱼8 小时前
使用 nvm 管理多 Node.js 版本 + pnpm 完整实操,解决 pnpm Node 版本报错
node.js
定栓9 小时前
Webpack迁到Vite第四节:SVG 图标系统
前端·webpack·node.js
小天源1 天前
智叟云集系统架构解析:从品牌 AI 可见度监测到前后端协同
人工智能·react.js·系统架构·node.js·react·ai监测·ai品牌监测
用户6122716650241 天前
电费 9 毛/天:我让一台 9 年前的旧 MacBook 替我上班,它比入门云服务器还能打
node.js
PegasusYu1 天前
Node.js使用nedb轻量级数据库测试脚本
数据库·electron·node.js·脚本·测试·轻量级·nedb
WebInfra1 天前
Rsdoctor 2.0 发布:Agent 驱动的全自动优化工具
前端·javascript·node.js