手机短信使用的第三方平台是联容云,注册就送8块钱体验费,足够自己用用了,注册完自己建一个应用就能拿到需要使用的配置了,如图

注册完之后1就可以使用了。

Node.js后端使用了Express框架

 "js-base64": "^3.7.2","blueimp-md5": "^2.19.0","moment": "^2.29.1","request": "^2.88.2"

这里引入了四个依赖

获取手机段短信方法

var md5 = require("blueimp-md5");
var moment = require("moment");
var Base64 = require("js-base64").Base64;
var request = require("request");/*生成指定长度的随机数*/
function randomCode(length) {var chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];var result = ""; //统一改名: alt + shift + Rfor (var i = 0; i < length; i++) {var index = Math.ceil(Math.random() * 9);result += chars[index];}return result;
}
// console.log(randomCode(6));
exports.randomCode = randomCode;/*
向指定号码发送指定验证码*/
function sendCode(phone, code, callback) {var ACCOUNT_SID = "";var AUTH_TOKEN = "";var Rest_URL = "";var AppID = "";//1. 准备请求url/*1.使用MD5加密(账户Id + 账户授权令牌 + 时间戳)。其中账户Id和账户授权令牌根据url的验证级别对应主账户。时间戳是当前系统时间,格式"yyyyMMddHHmmss"。时间戳有效时间为24小时,如:201404161420302.SigParameter参数需要大写,如不能写成sig=abcdefg而应该写成sig=ABCDEFG*/var sigParameter = "";var time = moment().format("YYYYMMDDHHmmss");sigParameter = md5(ACCOUNT_SID + AUTH_TOKEN + time);var url =Rest_URL +"/2013-12-26/Accounts/" +ACCOUNT_SID +"/SMS/TemplateSMS?sig=" +sigParameter;//2. 准备请求体var body = {to: phone,appId: AppID,templateId: "1",datas: [code, "1"],};//body = JSON.stringify(body);//3. 准备请求头/*1.使用Base64编码(账户Id + 冒号 + 时间戳)其中账户Id根据url的验证级别对应主账户2.冒号为英文冒号3.时间戳是当前系统时间,格式"yyyyMMddHHmmss",需与SigParameter中时间戳相同。*/var authorization = ACCOUNT_SID + ":" + time;authorization = Base64.encode(authorization);var headers = {Accept: "application/json","Content-Type": "application/json;charset=utf-8","Content-Length": JSON.stringify(body).length + "",Authorization: authorization,};//4. 发送请求, 并得到返回的结果, 调用callback// callback(true);request({method: "POST",url: url,headers: headers,body: body,json: true,},function (error, response, body) {callback(body.statusCode === "000000");});
}
exports.sendCode = sendCode;

使用:引入上面的方法,将请求的mobile和生成的code验证码传入进行保存在sendCodeP数组中进行保存,并开启计时器在120s后进行删除。

const { randomCode, sendCode } = require("../utils/getMessage");
const { valid } = require("../utils/valid")
var sqlQuery = require("../utils/dbconfig");
const jwt = require("../utils/token");let sendCodeP = []
//倒计时
setTime = function (mobile, code) {sendCodeP.push({mobile:mobile,code:code})let i = 0let timer = setInterval(() => {i += 1console.log(i)if (i == 120) {const index = sendCodeP.findIndex(e => {return e.mobile == mobile})sendCodeP.splice(index, 1)clearInterval(timer)}}, 1000);
}sendMobileCode = (req, res) => {const { mobile } = req.queryconsole.log(mobile)if (!valid.mobileFormatting.test(mobile)) {res.send({msg: "手机号格式错误",status: 402,});} else {const index=sendCodeP.findIndex(e=>{return e.mobile===mobile})if (index!=-1) {res.send({status: 402,msg: "已经发送过",});}else {let code = randomCode(6);sendCode(mobile, code, function (success) {if (success) {setTime(mobile, code)res.send({status: 0,msg: '短信验证码已发送'});} else {res.send({status: 402,msg: "短信验证码发送失败"});}});}}
}login = async function (mobile) {var sql = `select * from cms_user where mobile='${mobile}'`;let arr = []let data = await sqlQuery(sql, arr)return data
}//验证码登陆
codePhoneLogin = async (req, res) => {let { mobile, Verification } = req.query;console.log(sendCodeP, mobile)//验证手机号是否发送过验证码const index=sendCodeP.findIndex(e=>{return e.mobile===mobile})console.log(index)if (index!=-1) {//验证验证码与手机号是否匹配if (Verification==sendCodeP[index].code) {const loginData = await login(mobile)if (loginData && loginData.length != 0) {delete loginData[0]["password"];const tokenstr = jwt.encrypt({ gadID: loginData[0].id }, "2h");res.send({data: loginData[0],token: tokenstr,msg: `登录成功`,status: 0,});} else {res.send({msg: `无账号信息`,status: 402,});}} else {res.send({status: 402,msg: "验证码错误",});}} else {res.send({status: 402,msg: "请先获取验证码",});}
};
module.exports = {sendMobileCode,codePhoneLogin
}

Vue调用接口即可实现手机短信验证

附上前端短信登录代码

<template><div><el-form:model="ruleForm"status-icon:rules="rules_register"ref="ruleForm"label-width="60px"class="demo-ruleForm"><el-form-item label="手机号" prop="mobile"><el-input type="text" v-model="ruleForm.mobile" autocomplete="off"></el-input></el-form-item><el-form-item label="验证码" prop="Verification"><el-input style="width: 150px" v-model="ruleForm.Verification"></el-input><el-buttontype="primary"style="margin-left: 20px"@click="getCode":disabled="Boolean(timer)">{{btnName}}</el-button></el-form-item></el-form><div style="text-align: center"><el-button>重置</el-button><el-button type="primary" @click="submitForm('ruleForm')">登录</el-button></div></div>
</template><script>
export default {data() {var validateMobile = (rule, value, callback) => {if (!value) {callback(new Error("请输入手机号"));} else {if (!this.$valid.mobileFormatting.test(value)) {callback(new Error("请输入正确的手机号"));}callback();}};var validateVerification = (rule, value, callback) => {if (!value) {callback(new Error("请输入验证码"));} else {if (!this.$valid.VerificationFormatting.test(value)) {callback(new Error("请输入6位验证码"));}callback();}};return {ruleForm: {},timer: null,i: 0,btnName: "获取验证码",rules_register: {mobile: [{ validator: validateMobile, trigger: "blur" }],Verification: [{ validator: validateVerification, trigger: "blur" }]}};},methods: {getCode() {if (!this.ruleForm.mobile || this.ruleForm.mobile == "") {this.$message.error("请先输入手机号");return;} else if (!this.$valid.mobileFormatting.test(this.ruleForm.mobile)) {this.$message.error("手机号格式错误");return;} else {this.$getRequest("/sendCode", { mobile: this.ruleForm.mobile }).then(res => {if (res.status === 0) {this.$message.success(res.msg);this.timer = setInterval(() => {this.i += 1;this.btnName = `已发送(${60 - this.i})`;if (this.i === 60) {this.btnName = "重新获取";clearInterval(this.timer);}}, 1000);}});}},submitForm(formName) {this.$refs[formName].validate(valid => {if (valid) {this.$getRequest("/codePhoneLogin", this.ruleForm).then(res => {if (res.status == 0) {//  this.$message.success(`登录成功,欢迎你 ${res.data[0].name}`);let time = new Date().getHours();console.log(time);let title;if (time < 12) {title = "早上好";} else if (12 <= time && time < 18) {console.log(time);title = "下午好";} else {title = "晚上好";}this.$notify({title: "登录成功",message: title + "  " + res.data.name,type: "success"});this.$router.replace("/main");}});} else {console.log("error submit!!");return false;}});},resetForm(formName) {this.$refs[formName].resetFields();}}
};
</script><style>
</style>

手机短信验证登录就是这么简单,看过就能自己实现一个了。

Vue与Node.js实现手机短信验证登录相关推荐

  1. 瑞吉外卖项目中手机短信验证登录的问题及过程处理

    瑞吉外卖中手机短信验证码登陆的问题以及过程整理 本篇接上一篇文章: <基于SpringBoot+MybatisPlus开发的外卖管理项目>戳戳戳 http://t.csdn.cn/cRJY ...

  2. java+jsp如何实现发送手机短信验证登录

    我的qq  2038373094 1.借助第三方免费的sdk接口,下载java sdk http://smsow.zhenzikj.com/doc/sdk.html 下载后的SDK只包含一个jar文件 ...

  3. vue form 滑动验证码、手机短信验证

    话不多说直接上效果图 vue 注册首页 校验 滑动验证 页面源码 <template><div id="loginWrap"><div id=&quo ...

  4. win10一直正在检查更新_IT之家安卓/iOS版 7.15 更新:手机短信快捷登录/海外用户支持...

    IT之家 安卓和 iOS 版 7.15 更新! 这个版本是比较重大的版本,7.x 版本非常重视最底层.最基础的体验和功能,我们在陆续进行视觉方面(阅读细节.字体等)的调整后,开始对基础服务动刀,包括最 ...

  5. NODE.JS如何开发短信接口发送短信验证码/短信通知demo示例

    用户将收到的短信验证码填写到网站,网站对用户填写的验证码进行校验,如果一致,说明用户填写的手机号码是正确的,否则验证失败. 在开通手机短信验证功能之前,需要将网站同接口进行对接,对接的相关说明可以访问 ...

  6. 手机短信验证码登录功能的开发实录(机器识别码、短信限流、错误提示、发送验证码倒计时60秒)

    短信验证码登录功能 项目分析 核心代码 1.外部js库调用 2.HTML容器构建 3.javaScript业务逻辑验证 4.后端验证逻辑 总结 短信验证码是通过发送验证码到手机的一种有效的验证码系统, ...

  7. 小程序实现手机短信验证功能

    小程序实现手机短信验证功能 废话不多说,直接把项目写的手机短信验证功能发出来 .wxml <form bindsubmit="phone"> <input typ ...

  8. java手机短信验证,并存入redis中,验证码时效5分钟

    目录 1.注册发送短信账号一个账号 2.打开虚拟机,将redis服务端打开 3.创建springboot工程,导入相关依赖 4.写yml配置 5.创建controller层,并创建controller ...

  9. php中短信验证大致流程,实现php手机短信验证功能的基本思路

    现在很多网站为了避免用户烂注册,都在注册环节添加有手机短信验证功能,用户注册时需要短信验证码才可以,那么这种手机短信验证功能是如何实现的呢?其基本思路是什么呢?下面乐信小编就来为大家介绍下: 实现手机 ...

最新文章

  1. kotlin for android----------MVP模式下(OKHttp和 Retrofit+RxJava)网络请求的两种实现方式...
  2. Android --- 很好用的时间选择器
  3. Geolocation :基于浏览器的定位服务
  4. 12位故去的国家最高科技奖得主:科学寰宇,那些永不陨落的“星”
  5. 实战演练:通过伪列、虚拟列实现SQL优化
  6. Smarty3——foreach
  7. 跟着开源项目学因果推断——whynot(十四)
  8. 和老师们合作,注定了是打工的(转)
  9. office2019 使用
  10. 3.netwox网络工具集入门教程
  11. 基于稀疏表示字典学习的图像超分辨率-杨建超论文解析
  12. 上海,夜访大一女生宿舍,满足。
  13. 防火墙的目标地址转换和源地址转换
  14. [zt]软件研发的6sigma案例解析
  15. html如何加页脚,html-如何将页脚扩展到页面底部?
  16. HTML5制作一个笑脸
  17. 米兔机器人恐龙拼图手册_MI 小米 米兔积木机器人 履带版
  18. 服务器接显示器显示不支援,Win10专业版显示器输入不支援怎么办?如何解决?...
  19. chrome操作系统_如何在Chrome和Chrome操作系统上使用Google Play电影
  20. .Net 7里的函数.Ctor和.CCtor是干啥用的呢?你知道吗

热门文章

  1. 【三维目标检测】VoxelNet(一):crop.py详解
  2. 灰色GM(1,1)模型及其在电力负荷预测中的应用附Matlab代码
  3. 定义主函数main()
  4. 写公号半年,精品文章推荐
  5. [安装wireshark时,报“Error opening file for writing npf.sys”]
  6. 严格模式与混杂模式-如何触发这两种模式,区分它们有何意义
  7. 小酌Django1——Django基础
  8. TensorFlow学习--LeNet5神经网络
  9. mysql读写分离 abp_mysql读写分离策略
  10. POJ2010 Moo University - Financial Aid