使用koa框架写一个登录接口(可以使用管理员信息登录,登录后返回这个管理员除了密码之外的所有信息,token)
时间: 2023-07-16 22:15:22 浏览: 42
好的,以下是一个使用 Koa 框架编写的登录接口示例:
```javascript
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const jwt = require('jsonwebtoken');
const app = new Koa();
const router = new Router();
const secretKey = 'mySecretKey';
// 模拟管理员信息
const admin = {
username: 'admin',
password: '123456',
name: '管理员',
email: 'admin@example.com'
};
// 登录接口
router.post('/login', ctx => {
const { username, password } = ctx.request.body;
if (username === admin.username && password === admin.password) {
// 生成 token
const token = jwt.sign({ username: admin.username }, secretKey);
// 返回管理员信息和 token
ctx.body = {
username: admin.username,
name: admin.name,
email: admin.email,
token: token
};
} else {
ctx.status = 401; // 未授权
ctx.body = { message: '用户名或密码错误' };
}
});
app.use(bodyParser());
app.use(router.routes());
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
在上面的示例中,我们使用了 Koa 的中间件 `koa-bodyparser` 来解析请求体中的 JSON 数据,并使用了 JSON Web Token (JWT) 来生成和验证 token。在登录接口中,如果用户名和密码与预设的管理员信息匹配,则生成一个 token 并将管理员信息和 token 返回给客户端。如果用户名或密码不正确,则返回一个 HTTP 状态码为 401 的错误响应。