web验证码登录注册

This commit is contained in:
Ken 2025-03-12 11:23:35 +08:00
parent bc102248d7
commit 9ae23571be
6 changed files with 96 additions and 117 deletions

View file

@ -5,7 +5,7 @@ import user from './module/user.js'
* 在开发阶段,如果地址写的是相对路径,请与vue.config.js的devServer配置相结合,方便跨域请求 * 在开发阶段,如果地址写的是相对路径,请与vue.config.js的devServer配置相结合,方便跨域请求
* *
*/ */
const DEV_API_SERVICE = 'https://apifoxmock.com/m1/5931378-5618560-default' const DEV_API_SERVICE = 'http://localhost:8002/xiaozhi-esp32-api'
/** /**
* 根据开发环境返回接口url * 根据开发环境返回接口url

View file

@ -23,21 +23,42 @@ function sendRequest() {
_data: {}, _data: {},
_header: {'content-type': 'application/json; charset=utf-8'}, _header: {'content-type': 'application/json; charset=utf-8'},
_url: '', _url: '',
_responseType: undefined, // 新增响应类型字段
'send'() { 'send'() {
this._header.token = localStorage.getItem(Constant.STORAGE_KEY.TOKEN) this._header.token = localStorage.getItem(Constant.STORAGE_KEY.TOKEN)
// 打印请求信息
console.log('请求发送:', {
url: this._url,
method: this._method,
params: this._data,
headers: this._header,
responseType: this._responseType
});
fly.request(this._url, this._data, { fly.request(this._url, this._data, {
method: this._method, method: this._method,
headers: this._header headers: this._header,
responseType: this._responseType
}).then((res) => { }).then((res) => {
const error = httpHandlerError(res, this._failCallback) // 打印成功响应
console.log('请求成功:', {
status: res.status,
data: this._responseType === 'blob' ?
`Blob(${res.data.type}, ${res.data.size} bytes)` : res.data,
headers: res.headers
});
const error = httpHandlerError(res, this._failCallback);
if (error) { if (error) {
return return
} }
if (this._sucCallback) { if (this._sucCallback) {
this._sucCallback(res) this._sucCallback(res)
} }
}).catch((res) => { }).catch((res) => {
console.log(1111, res) // 打印失败响应
httpHandlerError(res, this._failCallback) httpHandlerError(res, this._failCallback)
}) })
return this return this
@ -75,6 +96,11 @@ function sendRequest() {
}, },
'async'(flag) { 'async'(flag) {
this.async = flag this.async = flag
},
// 新增类型设置方法
'type'(responseType) {
this._responseType = responseType;
return this;
} }
} }
} }
@ -84,11 +110,19 @@ function sendRequest() {
* callBack 回调函数 * callBack 回调函数
* errTip 自定义错误信息 * errTip 自定义错误信息
*/ */
// 在错误处理函数中添加日志
function httpHandlerError(info, callBack) { function httpHandlerError(info, callBack) {
console.log('响应处理:', {
status: info.status,
code: info.data?.code,
message: info.data?.msg
});
/** 请求成功,退出该函数 可以根据项目需求来判断是否请求成功。这里判断的是status为200的时候是成功 */ /** 请求成功,退出该函数 可以根据项目需求来判断是否请求成功。这里判断的是status为200的时候是成功 */
let networkError = false let networkError = false
if (info.status === 200) { if (info.status === 200) {
if (info.data.code === 'success' || info.data.code === 0) {
if (info.data.code === 'success' || info.data.code === 0 || info.data.code === undefined) {
return networkError return networkError
}else if (info.data.code === 401) { }else if (info.data.code === 401) {
goToPage(Constant.PAGE.LOGIN, true) goToPage(Constant.PAGE.LOGIN, true)

View file

@ -58,4 +58,23 @@ export default {
}); });
}).send() }).send()
}, },
getCaptcha(uuid, callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/api/v1/user/captcha?uuid=${uuid}`)
.method('GET')
.type('blob')
.header({
'Content-Type': 'image/gif',
'Pragma': 'No-cache',
'Cache-Control': 'no-cache'
})
.success((res) => {
RequestService.clearRequestTime();
callback(res);
})
.fail((err) => { // 添加错误参数
}).send()
},
} }

View file

@ -1,58 +0,0 @@
import axios from 'axios'
const api = axios.create({
baseURL: "http://localhost:8002/xiaozhi-esp32-api",
timeout: 30000,
})
// 请求拦截器
api.interceptors.request.use(config => {
// 打印请求信息
console.log('请求信息:', {
method: config.method.toUpperCase(),
url: config.baseURL + config.url,
params: config.params,
data: config.data
});
const token = localStorage.getItem('access_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
})
// 响应拦截器
api.interceptors.response.use(
response => {
// 打印响应信息
console.log('响应数据:', {
status: response.status,
data: response.data,
headers: response.headers
});
if (response.status !== 200) {
return Promise.reject(response.data)
}
return response
},
error => {
// 打印错误信息
console.error('请求错误:', {
status: error.response?.status,
data: error.response?.data,
message: error.message
});
if (error.response?.status === 401) {
localStorage.removeItem('access_token')
window.location.href = '/login'
}
return Promise.reject(error)
}
)
export default api

View file

@ -63,9 +63,9 @@
</template> </template>
<script> <script>
import axios from 'axios'
import { showDanger, showSuccess, goToPage } from '@/utils' import { showDanger, showSuccess, goToPage } from '@/utils'
import api from '@/apis/request' // 替换原来的Api导入 import Api from '@/apis/api';
export default { export default {
name: 'login', name: 'login',
@ -85,29 +85,19 @@ export default {
this.fetchCaptcha(); this.fetchCaptcha();
}, },
methods: { methods: {
async fetchCaptcha() { fetchCaptcha() {
this.captchaUuid = Date.now().toString() this.captchaUuid = Date.now().toString()
try {
// 添加请求地址打印 Api.user.getCaptcha(this.captchaUuid, ( res ) => {
console.log('请求地址:', api.defaults.baseURL+`/captcha?uuid=${this.captchaUuid}`) if(res.status == 200){
const response = await api.get(`/captcha?uuid=${this.captchaUuid}`, { const blob = new Blob([res.data], { type:res.data.type });
responseType: 'blob',
headers: {
'Content-Type': 'image/gif',
'Pragma': 'No-cache',
'Cache-Control': 'no-cache'
}
});
// 生成新的验证码URL
if (response.data) {
const blob = new Blob([response.data], { type: response.data.type });
this.captchaUrl = URL.createObjectURL(blob); this.captchaUrl = URL.createObjectURL(blob);
}
} } else {
catch (error) {
console.error('验证码加载异常:', error); console.error('验证码加载异常:', error);
showDanger('验证码加载失败,点击刷新'); showDanger('验证码加载失败,点击刷新');
} }
});
}, },
async login() { async login() {
@ -124,21 +114,21 @@ export default {
return return
} }
try { // try {
const response = await api.post('/user/login', { // const response = await api.post('/user/login', {
username: this.form.username, // username: this.form.username,
password: this.form.password, // password: this.form.password,
captcha: this.form.captcha, // captcha: this.form.captcha,
uuid: this.captchaUuid // uuid: this.captchaUuid
}) // })
showSuccess('登录成功!') // showSuccess('登录成功!')
goToPage('/home') // goToPage('/home')
} catch (error) { // } catch (error) {
const msg = error.response?.data?.msg || '登录失败' // const msg = error.response?.data?.msg || '登录失败'
showDanger(msg) // showDanger(msg)
this.fetchCaptcha() // 自动刷新验证码 // this.fetchCaptcha() // 自动刷新验证码
} // }
}, // ← 注意添加逗号分隔 }, // ← 注意添加逗号分隔
goToRegister() { goToRegister() {

View file

@ -84,7 +84,7 @@
<script> <script>
import { showDanger, showSuccess, goToPage } from '@/utils' import { showDanger, showSuccess, goToPage } from '@/utils'
import api from '@/apis/request' import Api from '@/apis/api';
export default { export default {
name: 'register', name: 'register',
@ -105,25 +105,19 @@ export default {
}, },
methods: { methods: {
// 复用验证码获取方法 // 复用验证码获取方法
async fetchCaptcha() { fetchCaptcha() {
this.captchaUuid = Date.now().toString() this.captchaUuid = Date.now().toString()
try {
const response = await api.get(`/captcha?uuid=${this.captchaUuid}`, { Api.user.getCaptcha(this.captchaUuid, ( res ) => {
responseType: 'blob', if(res.status == 200){
headers: { const blob = new Blob([res.data], { type:res.data.type });
'Content-Type': 'image/gif',
'Pragma': 'No-cache',
'Cache-Control': 'no-cache'
}
});
if (response.data) {
const blob = new Blob([response.data], { type: response.data.type });
this.captchaUrl = URL.createObjectURL(blob); this.captchaUrl = URL.createObjectURL(blob);
}
} catch (error) { } else {
console.error('验证码加载异常:', error); console.error('验证码加载异常:', error);
showDanger('验证码加载失败,点击刷新'); showDanger('验证码加载失败,点击刷新');
} }
});
}, },
// 注册逻辑 // 注册逻辑