实现一个简单的模拟后台数据,有登录
时间: 2023-05-27 20:07:41 浏览: 44
,注册,获取用户信息,修改用户信息等接口。
1. 登录接口
接口地址:/api/login
请求方式:POST
请求参数:
| 参数名 | 类型 | 描述 |
| -------- | ------ | ------ |
| username | string | 用户名 |
| password | string | 密码 |
返回参数:
| 参数名 | 类型 | 描述 |
| ------ | ------ | -------------------------- |
| code | number | 返回码,200表示登录成功 |
| msg | string | 返回信息 |
| data | object | 登录成功后返回的用户信息 |
示例代码:
```
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const users = [
{ id: 1, username: 'admin', password: '123456', name: '管理员' },
{ id: 2, username: 'user1', password: '123456', name: '用户1' },
{ id: 3, username: 'user2', password: '123456', name: '用户2' },
];
app.use(bodyParser.json());
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password === password);
if (user) {
res.json({
code: 200,
msg: '登录成功',
data: {
id: user.id,
username: user.username,
name: user.name,
},
});
} else {
res.json({
code: 400,
msg: '用户名或密码错误',
});
}
});
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});
```
2. 注册接口
接口地址:/api/register
请求方式:POST
请求参数:
| 参数名 | 类型 | 描述 |
| -------- | ------ | ------ |
| username | string | 用户名 |
| password | string | 密码 |
| name | string | 姓名 |
返回参数:
| 参数名 | 类型 | 描述 |
| ------ | ------ | ------------ |
| code | number | 返回码,200表示注册成功 |
| msg | string | 返回信息 |
示例代码:
```
app.post('/api/register', (req, res) => {
const { username, password, name } = req.body;
const user = users.find(u => u.username === username);
if (user) {
res.json({
code: 400,
msg: '该用户名已存在',
});
} else {
const id = users.length + 1;
users.push({ id, username, password, name });
res.json({
code: 200,
msg: '注册成功',
});
}
});
```
3. 获取用户信息接口
接口地址:/api/user/:id
请求方式:GET
请求参数:
| 参数名 | 类型 | 描述 |
| ------ | ------ | ------ |
| id | number | 用户ID |
返回参数:
| 参数名 | 类型 | 描述 |
| ------ | ------ | ------------ |
| code | number | 返回码,200表示获取成功 |
| msg | string | 返回信息 |
| data | object | 用户信息 |
示例代码:
```
app.get('/api/user/:id', (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
if (user) {
res.json({
code: 200,
msg: '获取成功',
data: {
id: user.id,
username: user.username,
name: user.name,
},
});
} else {
res.json({
code: 400,
msg: '用户不存在',
});
}
});
```
4. 修改用户信息接口
接口地址:/api/user/:id
请求方式:PUT
请求参数:
| 参数名 | 类型 | 描述 |
| ------ | ------ | ---------- |
| id | number | 用户ID |
| name | string | 修改后的姓名 |
返回参数:
| 参数名 | 类型 | 描述 |
| ------ | ------ | ------------ |
| code | number | 返回码,200表示修改成功 |
| msg | string | 返回信息 |
示例代码:
```
app.put('/api/user/:id', (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
if (user) {
user.name = req.body.name;
res.json({
code: 200,
msg: '修改成功',
});
} else {
res.json({
code: 400,
msg: '用户不存在',
});
}
});
```