# **依賴 svg-captcha**
## **拉取依賴**
```
npm i svg-captcha --save
```
## **創建驗證碼公共方法**
在util文件夾下創建Captcha.js文件
```
const svgCaptcha = require("svg-captcha");
const options = {
size: 4, // 驗證碼長度
ignoreChars: "0oO1ilI", // 驗證碼字符中排除 0oO1ilI
noise: 2, //干擾線條數
color: true, //驗證碼字體顏色
background: "#eee", //背景顏色
// ignoreChars: "0o1i", //驗證碼字符中排除 0o1i
// font: "30px Arial", //驗證碼字體
};
const Captcha = {
create: () => {
const captcha = svgCaptcha.create(options); // 生成驗證碼
const { text, data: img } = captcha; // 獲取驗證碼內容和svg
return { text, img };
},
};
module.exports = Captcha;
```
## **安裝sesstion存儲依賴**
```
npm i express-session --save
```
## **創建session中間件**
```
const session = require("express-session");
app.use(
session({
secret: "sessiontest", //與cookieParser中的一致
resave: true,
saveUninitialized: true,
})
);
```
## **登錄驗證**
```
const { captcha } = req.body; // 獲取用戶傳入的驗證碼
const sessionCaptcha = req.session.captcha; // 讀取session中的驗證碼
if (!captcha || captcha.toLowerCase() !== sessionCaptcha) {
res.send({ code: 401, msg: "驗證碼錯誤" });
return;
}
```
## **方法一:**
#### **創建驗證碼路由**
```
router.get("/getCaptcha", UserController.getCaptcha);
```
#### **app.js token驗證中間件添加白名單 `"/getCaptcha"`**
#### **創建controller**
在UserController.js中創建方法`getCaptcha`
```
getCaptcha: (req, res) => {
const { text, img } = Captcha.create();
req.session.captcha = text.toLowerCase(); // 將驗證碼文本存儲在session中
res.type("svg");
res.send({ code: 200, data: img });
},
```
#### **前端使用svg驗證碼并展示**
```
vue - html
<img :src="captchaUrl" @click="getCaptcha" />
vue - js
const captchaUrl = ref("");
const getCaptcha = () => {
axios.get("/api/getCaptcha").then((res) => {
if (res.data.code != 200) {
ElMessage.error(res.data.msg);
return;
}
captchaUrl.value = `data:image/svg+xml;charset=utf-8, ${encodeURIComponent(
res.data.data
)}`;
});
};
onMounted(() => {
getCaptcha();
});
```
## **方法二:**
#### **創建驗證碼路由**
```
router.get("/getCaptchaStream", UserController.getCaptchaStream);
```
#### **app.js token驗證中間件添加白名單 `"/getCaptchaStream"`**
#### **創建controller**
在UserController.js中創建方法`getCaptchaStream`
```
getCaptchaStream: (req, res) => {
const { text, img } = Captcha.create();
req.session.captcha = text.toLowerCase(); // 將驗證碼文本存儲在session中
res.type("svg");
res.send(img);
},
```
#### **前端使用svg驗證碼并展示**
```
vue - html
<img
:src="captchaStreamUrl"
class="captcha"
alt="驗證碼"
@click="getCaptchaStream"
/>
vue- js
const captchaStreamUrl = ref(`/api/getCaptchaStream?t=${Date.now()}`);
const getCaptchaStream = () => {
captchaStreamUrl.value = `/api/getCaptchaStream?t=${Date.now()}`;
};
```