欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 使用Node编写服务器接口

使用Node编写服务器接口

2025/2/22 2:12:51 来源:https://blog.csdn.net/weixin_39810558/article/details/144963787  浏览:    关键词:使用Node编写服务器接口

1.设置环境

打开终端输入如下命令:

mkdir apidemo
cd apidemo
npm init -y
npm install express
touch server.js

在server.js输入代码
 

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.运行服务器

打开终端输入

node server.js

3.验证接口

打开Postman查看请求结果

GET请求

POST请求

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词