使用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请求

相关推荐
程序员爱钓鱼1 天前
Node.js 编程实战:MongoDB 基础与 Mongoose 入门
后端·node.js·trae
程序员爱钓鱼1 天前
Node.js 编程实战:MySQL PostgreSQL数据库操作详解
后端·node.js·trae
古韵1 天前
当 API 文档走进编辑器会怎样?
vue.js·react.js·node.js
小胖霞2 天前
企业级全栈项目(14) winston记录所有日志
vue.js·前端框架·node.js
Anita_Sun2 天前
🎨 基础认知篇:打破单线程误区
node.js
Anita_Sun2 天前
😋 核心原理篇:线程池的 5 大核心组件
前端·node.js
孟祥_成都2 天前
nest.js / hono.js 一起学!字节团队如何配置多环境攻略!
前端·node.js
我爱学习_zwj2 天前
Node.js拦截器模式实现动态HTTP服务
网络协议·http·node.js
具***72 天前
MATLAB 风力发电系统低电压穿越之串电阻策略探索
node.js
你真的可爱呀2 天前
2.Express 核心语法与路由
中间件·node.js·express