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

相关推荐
20年编程老鸟java+ai全栈8 小时前
零基础搞定开发环境:PHP + Node.js + MongoDB + Python 一键安装全攻略
python·mongodb·node.js·php
ggaofeng13 小时前
实践NPM打包和使用
前端·npm·node.js
1telescope13 小时前
MacBook 安装 nvm 管理 Node.js 多版本教程
macos·node.js
ggaofeng13 小时前
理解npm的原理
前端·npm·node.js
卜锦元1 天前
EchoChat搭建自己的音视频会议系统01-准备工作
c++·golang·uni-app·node.js·音视频
weixin_427771611 天前
Vite 与 Webpack 模块解析差异
前端·webpack·node.js
鲨莎分不晴1 天前
【实战】老项目焕发新生:从 Webpack 平滑迁移到 Vite 避坑全记录
前端·webpack·node.js
中年程序员一枚2 天前
nuxt安装出现certificate 错误
前端框架·npm·node.js
虹科网络安全2 天前
艾体宝新闻 | Node.js 高危安全漏洞:堆栈溢出可能导致服务器崩溃(CVE-2025-59466)
node.js
JaredYe2 天前
纯 Node.js 的 PDF 转 Markdown 方案:支持图片解析的pdf2md库 `node-pdf-to-markdown`
pdf·node.js·markdown·md·pdf2md