使用Node编写服务器接口

1.设置环境

打开终端输入如下命令:

bash 复制代码
mkdir apidemo
cd apidemo
npm init -y
npm install express
touch server.js

在server.js输入代码

javascript 复制代码
const express = require('express');
const app = express();
const PORT = 3030;

// 中间件 - 解析JSON请求体
app.use(express.json());

// 示例数据存储
let users = [
  { id: 1, name: "Alice", age: 25 },
  { id: 2, name: "Bob", age: 30 },
];

// 首页路由
app.get('/', (req, res) => {
  res.send('Welcome to My API!');
});

// 获取所有用户
app.get('/users', (req, res) => {
  res.json(users);
});

// 根据ID获取单个用户
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).json({ error: 'User not found' });
  res.json(user);
});

// 添加新用户
app.post('/users', (req, res) => {
  const { name, age } = req.body;
  if (!name || !age) return res.status(400).json({ error: 'Name and age are required' });
  const newUser = { id: users.length + 1, name, age };
  users.push(newUser);
  res.status(201).json(newUser);
});

// 更新用户
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).json({ error: 'User not found' });

  const { name, age } = req.body;
  if (name) user.name = name;
  if (age) user.age = age;

  res.json(user);
});

// 删除用户
app.delete('/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
  if (userIndex === -1) return res.status(404).json({ error: 'User not found' });

  users.splice(userIndex, 1);
  res.status(204).send();
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

2.运行服务器

打开终端输入

bash 复制代码
node server.js

3.验证接口

打开Postman查看请求结果

GET请求

POST请求

相关推荐
Esun_R3 小时前
当 LLM 开始连接真实世界:MCP 的原理、通信与工程落地
node.js·openai·mcp
爱写程序的小高5 小时前
npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree
前端·npm·node.js
程序员爱钓鱼5 小时前
Node.js 编程实战:测试与调试 - 单元测试与集成测试
前端·后端·node.js
哟哟耶耶6 小时前
Plugin-webpack内置功能split-chunks-plugin配置打包代码分割
前端·webpack·node.js
SailingCoder7 小时前
AI 流式对话该怎么做?SSE、fetch、axios 一次讲清楚
前端·javascript·人工智能·ai·node.js
天远数科7 小时前
Node.js全栈实战:基于天远名下车辆数量查询API实现的智能资产核验组件
大数据·node.js
嫂子的姐夫7 小时前
013-webpack:新东方
爬虫·python·webpack·node.js·逆向
爱写程序的小高8 小时前
npm版本降级、nvm切换node版本、webpack版本与vue版本不一致
前端·npm·node.js
嚣张丶小麦兜9 小时前
npm的应用
前端·npm·node.js
在西安放羊的牛油果1 天前
浅谈 import.meta.env 和 process.env 的区别
前端·vue.js·node.js