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进行身份认证
  • 生产环境需要添加安全中间件和错误日志
相关推荐
用户0873086548713 小时前
用 GUI 自动化写了一个群聊 AI:5 个真实事故,和 7 条让 AI 不像机器人的设计
node.js
Dumbness2 天前
毕设后台导出 CSV 的 4 个坑:date 字段漏了公式防护,搜索框输入 % 能扫全表
node.js·express
wno7044 天前
node.js中使用jquery
前端·node.js·jquery
damoluomu4 天前
Node 的 Headless 出厂没有前台,Java 的 Headless 是从门户里长出来的
java·开发语言·node.js
Dumbness5 天前
一个手机号验证码登录接口的五个坑:无限发码、无限试码,传个数字就让 Express 进程退出
node.js·express
怒放的生命19915 天前
本地用 pnpm 省磁盘,团队继续用 npm:极简实践
前端·npm·node.js
Hone5 天前
我把「自动发文章到掘金」做成了一个 Agent 技能:juejin-skills
node.js·ai编程·前端工程化
Dumbness6 天前
二十行手写的 SKILL.md 头部解析,遇到 YAML 的折叠写法、单引号和嵌套键就读错:和 js-yaml 逐条对照
node.js·ai编程
只睡四小时6 天前
MCP 弃用 SSE?Node 分帧漏 81.7% 事件
node.js·webassembly·实时通信·mcp·streamable http