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进行身份认证
  • 生产环境需要添加安全中间件和错误日志
相关推荐
嘵奇27 分钟前
Node.js二:第一个Node.js应用
node.js
m0_748252389 小时前
Node.js HTTP模块详解:创建服务器、响应请求与客户端请求
服务器·http·node.js
m0_748234081 天前
Node.js使用教程
node.js·编辑器·vim
hamburgerDaddy11 天前
从零开始用react + tailwindcss + express + mongodb实现一个聊天程序(四) 实现注册功能
javascript·mongodb·react.js·intellij-idea·express
雲小妖1 天前
PowerShell 执行策略:fnm管理软件安装nodejs无法运行npm,错误信息:about_Execution_Policies
前端·npm·node.js
qq_530245191 天前
nvm下载node版本npm下载失败
前端·npm·node.js·nvm
Winson℡1 天前
在使用 npm link 进行本地 npm 包调试时,是否需要删除项目中已安装的依赖包取决于你的调试场景和依赖管理方式
前端·npm·node.js
糖果店的幽灵2 天前
Ubuntu 安装 Node.js 20.x
linux·ubuntu·node.js
AlgorithmAce2 天前
解决npm/yarn等包管理工具在vscode中使用出现系统禁止运行脚本的情况
前端·npm·node.js
超级无敌谢大脚2 天前
前端包管理工具进化论:npm vs yarn vs pnpm 深度对比
前端·npm·node.js