今天在写微信小程序时(模仿网易云音乐,根据网易云官方api接口文档,登录接口测试)
1.账号密码登录 //失效
2.手机号验证码登录 //无数据
3.邮箱登录 !!!可行
但是手机号验证码登录还是可以实现的,这是代码
/**
说明: 登录流程
1. 收集表单项数据
2. 前端验证
1) 验证用户账号是否合法
2) 前端验证不通过就提示用户,不需要发请求给后端
3) 前端验证通过了,发送请求给后端(后端再发验证码)
4) 用户填写验证码,点击登录,再对(账号,验证码)进一步验证。
3. 后端验证
1) 验证用户是否存在
2) 用户不存在直接返回,告诉前端用户不存在
3) 账号,验证码正确返回给前端数据,提示用户登录成功(会携带用户的相关信息)
*/
import request from '../../utils/request'
Page({
/**
* 页面的初始数据
*/
data: {
phone: '', // 手机号
captcha:'',//网易接口发的验证码
},
// 表单项内容发生改变的回调
handleInput(event){
// let type = event.currentTarget.id;// id传值 取值: phone || password
let type = event.currentTarget.dataset.type; // data-key=value
// console.log(event);
this.setData({
[type]: event.detail.value
})
},
// 点击发送验证码按钮
async sendCaptcha(){
if(!this.data.phone){
// 提示用户
wx.showToast({
title: '手机号不能为空',
icon: 'none'
})
return;
}
let phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;
if(!phoneReg.test(this.data.phone)){
wx.showToast({
title: '手机号格式错误',
icon: 'none'
})
return;
}
// 手机号码验证通过,发送验证码
let res=await request('/captcha/sent',{phone:this.data.phone})
if(res.code==200){
wx.showToast({
title:'验证码发送成功!',
icon:'success'
})
}
},
// 登录的回调
async login(){
// 1. 收集表单项数据
let {phone, captcha} = this.data;
// 2. 前端验证
/*
* 手机号验证:
* 1. 内容为空
* 2. 手机号格式不正确
* 3. 手机号格式正确,验证通过
* */
if(!phone){
// 提示用户
wx.showToast({
title: '手机号不能为空',
icon: 'none'
})
return;
}
// 定义正则表达式
let phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;
if(!phoneReg.test(phone)){
wx.showToast({
title: '手机号格式错误',
icon: 'none'
})
return;
}
if(!captcha){
wx.showToast({
title: '验证码不能为空',
icon: 'none'
})
return;
}
// 后端验证
let result = await request('/captcha/verify', {phone,captcha})
if(result.code === 200){ // 登录成功
console.log(result);
wx.showToast({
title: '登录成功'
})
}else if(result.code === 400){
wx.showToast({
title: '手机号错误',
icon: 'none'
})
}else if(result.code === 502){
wx.showToast({
title: '验证码错误',
icon: 'none'
})
}else {
wx.showToast({
title: '登录失败,请重新登录',
icon: 'none'
})
}
},
})