安装mews/captcha已经有笔记了,下面来说下前后端分离时该如何处理。
这里要知道一点,搭建好mews/captcha后,默认会开放
captcha/default
这个URL,如下:
http://localhost:81/captcha/default
这个就是获取验证码的url。
构造一个类,如下方法,构造出验证码:
- class CaptchaValidationController extends Controller
- {
- public function reloadCaptcha()
- {
- return response()->json([
- "imageUrl"=>Captcha::create("default",true)
- ]);
- }
- }
调用后可以看到:
关键就是这个key,图片内容是img,也就是说,前端把这个key、用户输入发送给后端。
后端通过这个key找到正确的验证码内容,和用户输入的做对比,就可以了。
前端如下:
验证码获取:
- function changeCaptchaImg(obj){
-
- axios("{{route("reloadCaptcha")}}")
- .then(function (response) {
-
- captchaKey = response.data.imageUrl.key;
- $('#captchaImg').prop('src', response.data.imageUrl.img);
- obj.onload = null;
-
- }).catch(function (err) {
-
- console.log(err)
- });
- }
对应的html如下:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAx9JREFUWEfNV89rE2EQfbPpbkKjZ21JtkEk2ehFqT+qeGgvxWKr+B/0oB5ERUEPPUgqXgSLB0VBPHgSDyqUqj2IYA+KqKmgWPODCs2m6kHx4qHNJvlGNpqQpPkSN67VHDOz8973Zubtt4R//KN28OdC/vVKMX+NCDvBrIKUFIvi2ehiYcZpPccE4t3o9HdoTwnYuhJM7DHMwjMnJBwTSOjaOAExCciUYVoH/iqBlK69Y2CzDISEJxBZXPpoxxMhXwiiOAjBaVl7pAokgt5BEO8mptdGNjdVBkzqWhxAr4xAUVG7FBR9iuAxBh8p5xEwJ0gcjmYKz6ufbUhghczMM0Y2P1A6VfMW3DdMa39K124yMNqA5De/sALBRSxVEatNe7MOfq9XSwPoro4wcC5qWuMLPZ1dy1ywVaiJ27kKaCSvdMQ9Iv9ZppACOhE2c1ekBFJBdTsTvWxQYNowrX32/3MhdYuHKcbMuwiKB0BKME9sylqT70NqnyKoRuaaWoRJI2MdlBKI90Jd86WkQKjmQcaEkbXOtJrwtO7bICA+yPIYGIua1gUpgVKfe9RLxHSqqsgsFay9kU/42oqAHW82qMS8I5LNv2pK4Oewqb0AjdjTa5jWnd8BLuekerxDzHy+flvKc9RyC5yANctNBNVRezCZMA+BW8ai9bY+37ETukVO2oJkBGuNFL67DSSrV1Gg2mCY+Wo0mz/mJon5gHdj0SOOgmmQoJwMm8uP7foVAvUez0IMtPN6lZFOBrVpEIZ+xWcN09pWQ6B+dRSi4XAm99AtFZJB9QmI+kv1qqy9okAyqF0E4XSJFeFFJGP1uQVeWutARz8RxUAUZuCGbes1CpSS7NcngOjC8oKb4M1q/X9ruFonb2nFq0WkaQvswXFzFRsdSkogpXuvl65UVSvjVBV7qBUhYoLpdjSbe+SIQFLXuPxAu6ZUcdcmh5BfSnX1MoGOu6EAge6FzdwDRwqUzUM2A/Z8KIrSJwCfBxSXAbRqW9s+kNS9NwA+VO/trQDr420TqLme/8Ggtk0grXuHBdj+TPMJ4G7Z21dNAadAsvwfJ6tAMMuA+kIAAAAASUVORK5CYII=" onload="changeCaptchaImg(this)" onclick="changeCaptchaImg(this)" id="captchaImg" />
发送axios给后端的代码:
- captcha = $('#captcha').val();
-
- let url = "{{route('RSAEncryption')}}";
-
- axios({
- method: "post",
- url: url,
- data: {
- key: captchaKey,
- captcha: captcha,
- msg: sendMsgText,
- RSAType: RSAType,
- AESType: AESType
- }
- }).then((res) => {
- console.log(res.data);
- })
后端接收的代码:
- if(!captcha_api_check($request->input('captcha'), $request->input('key'))){
-
- return response()->json([
- 'error' => '验证码有误'
- ]);
- }
-
- return response()->json([
- 'success' => '验证码正确'
- ]);
关键就是这个catcha_api_check函数,第一个是用户输入的验证码,第二个是key。