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

相关推荐
知否技术6 小时前
Node登陆认证实战!10分钟手把手教会你!
后端·node.js
斯~内克8 小时前
深入探索Node.js Koa框架:构建现代化Web应用的2000字实践指南
前端·node.js
mercyT8 小时前
npm i 出现的网络问题
前端·npm·node.js
竺梓君10 小时前
前端必懂优化策略——浏览器缓存
前端·javascript·node.js
小浣熊喜欢揍臭臭12 小时前
webpack配置详解+项目实战
前端·webpack·node.js
coding随想12 小时前
解决 macOS (M1 Pro) 上使用 Vite 进行 Build 打包时 Node 进程内存溢出的问题
macos·node.js
henujolly1 天前
node.js学习
node.js
red润2 天前
npm包autocannon牛逼的后台压力测试库
前端·javascript·node.js
Ethan_Zhou【数据恢复专家】2 天前
Node.js 性能提升秘籍:多线程与 HTTP 并发管理策略
网络协议·http·node.js
程序员差不多先生2 天前
如何在阿里云linux主机上部署Node.Js
阿里云·node.js