发布于 

【Node专栏】登录页面实现简单验证码功能

一、简介

虽然在以往的工作中,都是接入公司的统一登录,不会说用单独的这种登录界面。但是如果自己做一个系统要给别人用,最起码搞个简单的验证码登录,相比短信验证码需要收费,那一般先搞个验证码登录。

二、实现方式

2.1 安装依赖

安装依赖:使用 npm 安装 koakoa-session@koa/routersvg-captcha 模块。

2.2 Koa代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const Koa = require('koa');
const Router = require('@koa/router');
const session = require('koa-session');
const svgCaptcha = require('svg-captcha');

const app = new Koa();
const router = new Router();

app.keys = ['your-session-secret-key'];

// 添加 session 中间件
app.use(session(app));

// 生成验证码并返回 SVG 图像
router.get('/captcha', (ctx) => {
const captcha = svgCaptcha.create();
ctx.session.captcha = captcha.text;
ctx.type = 'svg';
ctx.body = captcha.data;
});

router.post('/login', (ctx) => {
const { username, password, captcha } = ctx.request.body;
if (captcha !== ctx.session.captcha) {
ctx.body = 'Invalid captcha';
} else if (username === 'admin' && password === 'password') {
ctx.body = 'Login successful';
} else {
ctx.body = 'Invalid username or password';
}
});

router.get('/index', (ctx)=>{
ctx.body = `
<html>
<head>
<title>hell world</title>
</head>
<body>
<form action="/login" method="post">
<label for="username">Username:</label>
<input type="text" name="username" id="username">

<label for="password">Password:</label>
<input type="password" name="password" id="password">

<label for="captcha">Captcha:</label>
<img src="/captcha" alt="Captcha">
<input type="text" name="captcha" id="captcha">

<button type="submit">Login</button>
</form>
</body>
</html>`
})

app.use(router.routes());
app.listen(3000, () => {
console.log('Server started on port 3000');
});

在上面的代码中,我们首先获取用户提交的表单数据,包括用户名、密码和验证码。然后,我们检查验证码是否与会话中的验证码相同,如果不同则返回“Invalid captcha”错误信息。如果验证码正确,则检查用户名和密码是否正确,并返回相应的消息。

三、总结

在企业中一般会通过接入企业的统一登录,下次再写一篇github登录为例子,搞一个博客的登录留言吧。


如果你有什么意见和建议,可以点击: 反馈地址 进行反馈。