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

相关推荐
Java陈序员2 小时前
自建 Claude Code 镜像!一站式开源中转服务!
docker·node.js·vue·claude·claude code
qinqinzhang4 小时前
dotenv详解
node.js
givemeacar6 小时前
nvm下载安装教程(node.js 下载安装教程)
node.js
AAA阿giao8 小时前
从零到精通 NestJS:深度剖析待办事项(Todos)项目,全面解析 Nest 架构、模块与数据流
架构·typescript·node.js·nestjs·全栈开发·后端框架
朝朝暮暮an9 小时前
Day 13|接口安全、限流 & 防御策略 And Day 14|后端项目结构 & 实战项目整合
node.js
回到原点的码农10 小时前
Node.js 与 Docker 深度整合:轻松部署与管理 Node.js 应用
docker·容器·node.js
bearpping10 小时前
Node.js NativeAddon 构建工具:node-gyp 安装与配置完全指南
node.js
splage10 小时前
Node.js实现WebSocket教程
websocket·网络协议·node.js
mcooiedo10 小时前
Node.js(v16.13.2版本)安装及环境配置教程
node.js
ywf121510 小时前
Node.js使用教程
node.js·编辑器·vim