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

相关推荐
醇氧3 小时前
【teambition 二开】创建计划工时
node.js·teambition
小新1104 小时前
vscode+nodejs+express 搭建一个简单网站
vscode·node.js·express
浩泽学编程5 小时前
内网开发?系统环境变量无权限配置?快速解决使用其他版本node.js
前端·vue.js·vscode·node.js·js
大布布将军6 小时前
⚡部署的通行证:Docker 容器化基础
运维·前端·学习·程序人生·docker·容器·node.js
薛定谔的猫-菜鸟程序员6 小时前
基于Node.js+Pandoc实现Markdown文件无损转换为Word文档的小工具
node.js·word·vim
2501_942818911 天前
AI 多模态全栈项目实战:Vue3 + Node 打造 TTS+ASR 全家桶!
vue.js·人工智能·node.js
前端流一1 天前
[疑难杂症] 浏览器集成 browser-use 踩坑记录
前端·node.js
大布布将军1 天前
⚡后端安全基石:JWT 原理与身份验证实战
前端·javascript·学习·程序人生·安全·node.js·aigc
闲云一鹤1 天前
【工具篇】使用 nvm 进行 node 版本管理
前端·npm·node.js
小白咚1 天前
npm在文件下输入运行命令,授权限制问题window
前端·npm·node.js