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进行身份认证
  • 生产环境需要添加安全中间件和错误日志
相关推荐
前端之虎陈随易3 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·vue.js·人工智能·typescript·node.js
meilindehuzi_a16 小时前
从零开始:用原生 Node.js 徒手拆解 RAG 与向量检索底层原理
node.js·rag
炒毛豆16 小时前
ai全栈-node.js相关的学习之路(草稿版)
学习·node.js
meilindehuzi_a18 小时前
解密 MCP 协议:如何用 Node.js 从零手写一个本地文件读取 MCP 服务器
运维·服务器·node.js
hoLzwEge4 天前
pnpm vs npm:新一代包管理器的范式革命
前端框架·node.js
麻辣凉茶4 天前
给阿嬤一封来自云端的信(上)
前端·node.js
codingWhat5 天前
能效平台设计方案(打通gitlab和飞书)
后端·node.js·koa
见过夏天6 天前
Node.js 常用命令全攻略
node.js
前端双越老师7 天前
我从 0 开发的 AI Agent 智语项目发布了
前端·node.js·agent
kyriewen7 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js