一:说在前面
我是已经开通了阿里云的短信服务功能
创建Node项目
我的Node项目:my-node-project
二、Node代码块
新建app.js
// app.js
const express = require('express');
const app = express();
const loginRouter = require('./routes/login');
app.use(express.json());
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080"); // 明确指定允许的源
res.header("Access-Control-Allow-Credentials", "true"); // 允许服务器接受请求中的 cookies
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use('/login', loginRouter);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
在routes 文件夹下新建login.js
// routes/login.js
const express = require('express');
const router = express.Router();
const SMSClient = require('@alicloud/sms-sdk');
const accessKeyId = 'LTAI5tQ4hCB4sQQjBKqbimwT';
const secretAccessKey = 'JOJVEEUGyNi2Hh9jEMo5mCRNhDj8Ii';
const smsClient = new SMSClient({ accessKeyId, secretAccessKey });
router.get('/', function(req, res) {
const phoneNum = req.query.phoneNum;
//const code = Math.floor(1000 + Math.random() * 9000); // Generate a 4-digit code
const code = Math.floor(100000 + Math.random() * 900000); // Generate a 6-digit code
smsClient.sendSMS({
PhoneNumbers: phoneNum,
SignName: '超脑系统',
TemplateCode: 'SMS_465925761',
TemplateParam: `{"code": "${code}"}`
}).then(function(response) {
if (response.Code === 'OK') {
res.send({ msg: "ok", code });
} else {
res.status(500).send({ msg: "fail" });
}
}).catch(function(err) {
res.status(500).send({ msg: "fail", error: err });
});
});
module.exports = router;
三、vue代码块
<template>
<div class="login-container">
<form class="login-box" @submit.prevent="handleRegister">
<h1>注册</h1>
<div v-if="errorMessage" class="error-message">
<span class="iconfont icon-error">{{ errorMessage }}</span>
</div>
<div v-if="successMessage" class="success-message">
{{ successMessage }}
</div>
<div class="input-box">
<label class="input-text">
<span class='iconfont icon-phone'></span>
+86 <input type="text" placeholder="输入手机号" v-model="phone">
</label>
<label class="input-text verification">
<input type="text" placeholder="请输入校验码" v-model="verificationCode">
<button @click.prevent="sendVerificationCode" class="send-code" :disabled="countdown > 0">
{{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
</button>
</label>
<button type="submit" class="input-btn">注册</button>
</div>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'RegisterComponent',
data() {
return {
username: '',
password: '',
confirmPassword: '',
phone: '',
verificationCode: '',
errorMessage: '',
successMessage: '',
countdown: 0,
correctCode: '' // This will store the correct code from the server
};
},
methods: {
handleRegister() {
if (!/^1[3-9]\d{9}$/.test(this.phone)) {
this.errorMessage = '请输入有效的手机号码❌';
this.clearErrorMessage();
return;
}
if (!this.verificationCode) {
this.errorMessage = '请输入验证码❌';
this.clearErrorMessage();
return;
}
if (parseInt(this.verificationCode) !== this.correctCode) {
this.errorMessage = '验证码错误❌';
this.clearErrorMessage();
return;
}
this.successMessage = '身份验证成功✅';
setTimeout(() => {
this.navigateToAnotherPage();
}, 2000);
console.log("注册信息:", this.username, this.password, this.phone, this.verificationCode);
},
sendVerificationCode() {
// 验证必填字段
if (!this.username || !this.password || !this.confirmPassword || !this.phone) {
this.errorMessage = '所有字段都是必填项❌';
this.clearErrorMessage();
return;
}
// 验证密码是否一致
if (this.password !== this.confirmPassword) {
this.errorMessage = '两次输入的密码不匹配❌';
this.clearErrorMessage();
return;
}
// 验证手机号格式
if (!/^1[3-9]\d{9}$/.test(this.phone)) {
this.errorMessage = '请输入有效的手机号码❌';
this.clearErrorMessage();
return;
}
// 如果所有验证通过,开始发送验证码并启动倒计时
if (this.countdown > 0) return;
this.startCountdown();
axios.get(`http://localhost:3000/login?phoneNum=${this.phone}`)
.then(res => {
console.log('Response:', res.data);
this.correctCode = res.data.code; // Store the correct code from the server
console.log('验证码为:', this.correctCode);
})
.catch(err => {
console.error('Error:', err);
});
},
startCountdown() {
this.countdown = 60;
const interval = setInterval(() => {
this.countdown--;
if (this.countdown === 0) clearInterval(interval);
}, 1000);
},
navigateToAnotherPage() {
this.$router.push('/login');
},
clearErrorMessage() {
setTimeout(() => {
this.errorMessage = '';
}, 2000);
}
}
}
</script>
<style scoped>
.login-container {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
min-height: 100vh;
}
.login-box {
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
width: 700px;
height: 580px;
background-color: rgba(0,0,0,.5);
padding: 20px 50px;
border-radius: 20px;
}
.icon-error {
margin-right: 10px;
}
.input-box {
width: 50%;
}
.input-text {
display: flex;
align-items: center;
margin-top: 30px;
}
.input-text span {
color: white;
font-size: 20px;
}
.input-text input {
flex-grow: 1;
border: none;
padding: 6px;
border-bottom: 1px solid white;
background-color: transparent;
color: #fff;
margin-left: 10px;
font-size: 15px;
}
.input-btn, .send-code {
height: 40px;
width: 100%;
color: #fff;
background: linear-gradient(120deg,#a6c0fe 0%,#f68084 100%);
border-radius: 25px;
cursor: pointer;
}
.input-btn {
margin-top: 25px;
}
.send-code {
width: auto;
padding: 0 20px;
margin-left: 10px; /* Add space between input and button */
}
.verification {
justify-content: space-between; /* Aligns the input and button nicely */
}
.error-message {
color: #ff3860;
background-color: #ffebee;
padding: 10px;
border-radius: 5px;
margin-bottom: 10px;
width: 100%;
text-align: center;
}
.success-message{
color: green;
background-color: #ffebee;
padding: 10px;
border-radius: 5px;
margin-bottom: 10px;
width: 100%;
text-align: center;
}
</style>
四、启动
启动node
cd my-node-project
node app.js
启动vue
npm run serve
五、效果:
补充
以上是使用阿里云短信服务功能的基本方法。根据你的具体需求修改。
笔者水平有限,如有不当之处,请予指正~
非常感谢各位耐心观看!如果看到这句话,并且觉得有用的话,不妨点个赞呗~~~