如何用vue来写验证码+登录

3 篇文章 0 订阅

如何用vue来写验证码+登录

该项目需要在登录之前添加验证码,为了更加方便请求接口的区分,可以封装两个请求接口,一个登录之前需要请求的接口,一个为登录之后请求的接口,使之互不干扰。
1.登录前设置一个文件夹axios,其中的index.js写请求的接口,config写配置

index.js


/*接口文件*/
//axios配置文件
import index from './config'

export default {
    API_VERIFY: (params) => index('get', '/login/getverify?', params),//验证码

    API_LOGIN: (body ) => index('post','login/index?' ,body),//登录
   
}

cofig.js
import axios from 'axios'
import index from './index'

const instance = axios.create({
    //默认地址
    baseURL: 'http://192.0.0.0',
    //响应时长
    timeout: 6000
})

//请求拦截器
instance.interceptors.request.use(
    /**
     * @param config    传入的url以及参数
     */
    (config) => {
        axios.defaults.headers['Content-Type'] = 'Access-Control-Allow-Origin'
        // console.log("发送请求",config)
        return config
    },
    (error) => {
        console.log("发送请求失败")
        return Promise.reject(error)
    }
)

//响应拦截器
instance.interceptors.response.use(
    (response) => {
        // console.log("响应成功",response)
        return response.data
    },
    (error) => {
        console.log("响应失败",error.response)
        return Promise.reject(error)
    }
)
/**
 * @param {请求方式} method 
 * @param {请求地址} path 
 * @param {请求参数} params
 */
export default function (method, url, params) {
    method = method.toLowerCase()
    switch (method) {
        case 'get':
            params = params || ''
            return instance.get(url + params)
        case 'post':
            params = params || null
            return instance.post(url,params)
        default:
        console.error('未知的method:'+method)
        return false
    }
}

在main.js

import index from './axios/index';
Vue.prototype.$index = index

在需要的页面调用你在index.js里面设置的请求接口名
列:登录页面login.vue

 this.$index.API_LOGIN(obj).then(res=>{
 console.log(res)})
 .catch(err=>{
 console.log(err)})

其它页面也相应的调用即可,然后用相同方法再封装一个登录后的axios请求方法。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Vue和Spring Boot的验证码登录,需要以下步骤: 1. 在Vue中创建一个登录页面,包括用户名、密码和验证码输入框,以及一个登录按钮。 2. 在Vue中使用axios或其他HTTP库向后端发送登录请求,包括用户名、密码和验证码。 3. 在Spring Boot中创建一个控制器,用于处理登录请求。在控制器中,可以使用Spring Security提供的AuthenticationManager来验证用户名和密码是否正确,并使用自定义的验证码验证器来验证验证码是否正确。 4. 如果用户名、密码和验证码都正确,则在后端生成一个JWT令牌,并将令牌返回给前端。 5. 在Vue中,如果收到登录成功的响应,则将JWT令牌保存在本地存储中,并将用户重定向到主页。 以下是一个简单的示例: Vue代码: ``` <template> <div> <h1>登录</h1> <form> <label>用户名</label> <input type="text" v-model="username"><br> <label>密码</label> <input type="password" v-model="password"><br> <label>验证码</label> <input type="text" v-model="captcha"><br> <img :src="captchaUrl" @click="refreshCaptcha"><br> <button type="button" @click="login">登录</button> </form> </div> </template> <script> import axios from 'axios'; export default { data() { return { username: '', password: '', captcha: '', captchaUrl: '', }; }, methods: { login() { axios.post('/api/login', { username: this.username, password: this.password, captcha: this.captcha, }).then(response => { localStorage.setItem('token', response.data.token); this.$router.push('/home'); }).catch(error => { alert(error.response.data.message); }); }, refreshCaptcha() { this.captchaUrl = '/api/captcha?' + Math.random(); }, }, mounted() { this.refreshCaptcha(); }, }; </script> ``` Spring Boot代码: ``` @RestController @RequestMapping("/api") public class LoginController { @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private CaptchaValidator captchaValidator; @PostMapping("/login") public ResponseEntity<?> login(@RequestBody LoginRequest request) { try { // 验证验证码 captchaValidator.validate(request.getCaptcha()); // 验证用户名和密码 UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( request.getUsername(), request.getPassword()); Authentication authentication = authenticationManager.authenticate(token); // 生成JWT令牌 String jwtToken = jwtTokenUtil.generateToken(authentication); return ResponseEntity.ok(new LoginResponse(jwtToken)); } catch (AuthenticationException | CaptchaException e) { return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage())); } } @GetMapping("/captcha") public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException { // 生成验证码图片并返回 Captcha captcha = captchaValidator.generateCaptcha(); String captchaId = captcha.getId(); BufferedImage image = captcha.getImage(); response.setHeader("Cache-Control", "no-cache, no-store"); response.setContentType("image/jpeg"); ImageIO.write(image, "jpeg", response.getOutputStream()); // 将验证码ID保存在Session中 HttpSession session = request.getSession(true); session.setAttribute("captchaId", captchaId); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值