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

相关推荐
freewlt4 小时前
VS Code 扩展开发:集成 GitHub Copilot 的完整指南
vscode·node.js
技术程序猿华锋6 小时前
OpenAI GPT Image 2 教程:API Key 获取、参数说明与 Python/Node.js 示例
python·gpt·node.js·ai绘画
米丘9 小时前
vue3.x 编译 script setup 编译过程
vue.js·node.js·babel
网络点点滴10 小时前
Node.js从URL中解析变量
node.js
火乐暖阳8510510 小时前
vue3+node.js:一个基础入门的全栈CURD模块
node.js
zhensherlock11 小时前
Protocol Launcher 系列:Working Copy 提交与同步全攻略
javascript·git·typescript·node.js·自动化·github·js
无巧不成书02181 天前
2026最新Next-AI-Draw-io全攻略:AI驱动专业图表生成,Docker/Node.js本地部署零踩坑指南
人工智能·docker·node.js·next-ai-draw-io
悟空瞎说1 天前
我踩过的4个Node.js微服务经典Bug,用一个库彻底解决(2000字详解+可直接复用代码)
后端·node.js
捉鸭子1 天前
某红书X-s X-s-common VMP逆向(算法还原)
python·web安全·网络安全·node.js·网络爬虫
freewlt1 天前
Node.js 性能分析实战指南:从入门到精通
node.js