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

相关推荐
嘵奇10 分钟前
Node.js二:第一个Node.js应用
node.js
m0_748252389 小时前
Node.js HTTP模块详解:创建服务器、响应请求与客户端请求
服务器·http·node.js
m0_748234081 天前
Node.js使用教程
node.js·编辑器·vim
雲小妖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
i建模2 天前
Windows前端开发IDE选型全攻略
前端·ide·windows·node.js·编辑器·visual studio code