JavaScript中如何校驗接口是否重復(fù)提交
JS校驗接口重復(fù)提交
示例代碼
request.js
import axios from 'axios'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from "@/utils/ruoyi";
import cache from '@/plugins/cache'
import { saveAs } from 'file-saver'
let downloadLoadingInstance;
// 是否顯示重新登錄
export let isRelogin = { show: false };
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 創(chuàng)建axios實例
const service = axios.create({
// axios中請求配置有baseURL選項,表示請求URL公共部分
baseURL: process.env.VUE_APP_BASE_API,
// 超時
timeout: 10000
})
// 請求攔截器
service.interceptors.request.use(config => {
// 是否需要設(shè)置 token
const isToken = (config.headers || {}).isToken === false
// 是否需要防止數(shù)據(jù)重復(fù)提交
const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
if (getToken() && !isToken) {
config.headers['Authorization'] = 'Bearer ' + getToken() // 讓每個請求攜帶自定義token 請根據(jù)實際情況自行修改
}
// get請求映射params參數(shù)
if (config.method === 'get' && config.params) {
let url = config.url + '?' + tansParams(config.params);
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
const requestObj = {
url: config.url,
data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
time: new Date().getTime()
}
const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 請求數(shù)據(jù)大小
const limitSize = 5 * 1024 * 1024; // 限制存放數(shù)據(jù)5M
if (requestSize >= limitSize) {
console.warn(`[${config.url}]: ` + '請求數(shù)據(jù)大小超出允許的5M限制,無法進(jìn)行防重復(fù)提交驗證。')
return config;
}
const sessionObj = cache.session.getJSON('sessionObj')
if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
cache.session.setJSON('sessionObj', requestObj)
} else {
const s_url = sessionObj.url; // 請求地址
const s_data = sessionObj.data; // 請求數(shù)據(jù)
const s_time = sessionObj.time; // 請求時間
const interval = 1000; // 間隔時間(ms),小于此時間視為重復(fù)提交
//此處校驗是否是重復(fù)提交
if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
const message = '數(shù)據(jù)正在處理,請勿重復(fù)提交';
console.warn(`[${s_url}]: ` + message)
return Promise.reject(new Error(message))
} else {
cache.session.setJSON('sessionObj', requestObj)
}
}
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
// 響應(yīng)攔截器
service.interceptors.response.use(res => {
// 未設(shè)置狀態(tài)碼則默認(rèn)成功狀態(tài)
const code = res.data.code || 200;
// 獲取錯誤信息
const msg = errorCode[code] || res.data.msg || errorCode['default']
// 二進(jìn)制數(shù)據(jù)則直接返回
if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
return res.data
}
if (code === 401) {
if (!isRelogin.show) {
isRelogin.show = true;
// MessageBox.confirm('登錄狀態(tài)已過期,您可以繼續(xù)留在該頁面,或者重新登錄', '系統(tǒng)提示', { confirmButtonText: '重新登錄', cancelButtonText: '取消', type: 'warning' }).then(() => {
// isRelogin.show = false;
// store.dispatch('LogOut').then(() => {
// location.href = '/index';
// })
// }).catch(() => {
// isRelogin.show = false;
// });
}
return Promise.reject('無效的會話,或者會話已過期,請重新登錄。')
} else if (code === 500) {
Message({ message: msg, type: 'error' })
return Promise.reject(new Error(msg))
} else if (code === 601) {
Message({ message: msg, type: 'warning' })
return Promise.reject('error')
} else if (code === 1) {
return res.data
} else if(res.code !== 200){
Notification.error({ title: msg })
return Promise.reject('error')
} else{
return res.data
}
},
error => {
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = "后端接口連接異常";
} else if (message.includes("timeout")) {
message = "系統(tǒng)接口請求超時";
} else if (message.includes("Request failed with status code")) {
message = "系統(tǒng)接口" + message.substr(message.length - 3) + "異常";
}
Message({ message: message, type: 'error', duration: 5 * 1000 })
return Promise.reject(error)
}
)
// 通用下載方法
export function download(url, params, filename, config) {
downloadLoadingInstance = Loading.service({ text: "正在下載數(shù)據(jù),請稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
return service.post(url, params, {
transformRequest: [(params) => { return tansParams(params) }],
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
responseType: 'blob',
...config
}).then(async (data) => {
const isBlob = blobValidate(data);
if (isBlob) {
const blob = new Blob([data])
saveAs(blob, filename)
} else {
const resText = await data.text();
const rspObj = JSON.parse(resText);
const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
Message.error(errMsg);
}
downloadLoadingInstance.close();
}).catch((r) => {
console.error(r)
Message.error('下載文件出現(xiàn)錯誤,請聯(lián)系管理員!')
downloadLoadingInstance.close();
})
}
export default service方法補(bǔ)充
除了上文的方法,小編還為大家整理了一些其他JavaScript接口防重復(fù)提交的方法,希望對大家有所幫助
方法一:js防止重復(fù)提交接口
思路:定義一個事件的標(biāo)識變量為false,點擊事件里先判斷變量是否為true,是的話就不執(zhí)行,否者的話把變量改為true,之后再執(zhí)行點擊事件內(nèi)容即可。
下方代碼表示只執(zhí)行一次
let isFlag= false;
//點擊事件
$(document).on("click","#_submit",function (){
if (isFlag) {
return false;
}
isFlag= true;
//執(zhí)行內(nèi)容。。。。。
})
方法二:防止重復(fù)點擊
定義一個clickThrottle.js文件
/* 防止重復(fù)點擊 */
let clickTimer = 0
function clickThrottle(interval = 3000) {
let now = +new Date(); // 獲取當(dāng)前時間的時間戳
let timer = clickTimer; // 記錄觸發(fā)事件的事件戳
if (now - timer < interval) {
// 如果當(dāng)前時間 - 觸發(fā)事件時的事件 < interVal,那么不符合條件,直接return false,
// 不讓當(dāng)前事件繼續(xù)執(zhí)行下去
return false;
} else {
// 反之,記錄符合條件觸發(fā)了事件的時間戳,并 return true,使事件繼續(xù)往下執(zhí)行
clickTimer = now;
return true;
}
}
export default clickThrottle
+new Date()這個代碼是獲得當(dāng)前時間的時間戳,與 new Date().getTime() 、 new Date().valueOf() 以及 Date.now() 是一樣的。
方法三:兩種防止js重復(fù)執(zhí)行的方法
其一:
function test(){
console.log(0);
}
function throttle(fun){
if(fun.timeoutId) {window.clearTimeout(fun.timeoutId);}
fun.timeoutId = window.setTimeout(function(){
fun();
fun.timeoutId = null;
}, 1000);
}
throttle(test);
throttle(test);
throttle(test);
throttle(test);其二:
//禁用按鈕
$('button').prop('disabled',true);
//回調(diào)函數(shù)啟用按鈕
$('button').prop('disabled',false);
如果想要最后一次點擊生效,把timer定時器放在函數(shù)外每次調(diào)用進(jìn)行檢測;如果不涉及定時器,就在函數(shù)內(nèi)部把函數(shù)賦值給自己讓每次調(diào)用都執(zhí)行新的邏輯
var timer;
var foo = function() {
timer && clearTimeout(timer);
timer = setTimeout(function() {
console.log(0);
}, 5000);
//something
}到此這篇關(guān)于JavaScript中如何校驗接口是否重復(fù)提交的文章就介紹到這了,更多相關(guān)JavaScript接口重復(fù)提交內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
多次注冊事件會導(dǎo)致一個事件被觸發(fā)多次的解決方法
一個JavaScript邏輯,會自動綁定函數(shù)到按鈕的click事件,但是這段代碼會反復(fù)注冊事件,具體的解決方法如下,感興趣的朋友可以參考下2013-08-08
ionic App問題總結(jié)系列之ionic點擊系統(tǒng)返回鍵退出App
本篇文章主要介紹了ionic App問題總結(jié)系列之ionic點擊系統(tǒng)返回鍵退出App,具有一定的參考價值,有興趣的可以了解一下2017-08-08
解決layui table表單提示數(shù)據(jù)接口請求異常的問題
今天小編就為大家分享一篇解決layui table表單提示數(shù)據(jù)接口請求異常的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09
js實現(xiàn)使用輸入input和改變change事件模擬手動輸入
聚焦于JavaScript中的輸入模擬技術(shù),本指南將帶你探索如何使用input和change事件來創(chuàng)造逼真的手動輸入效果,通過簡單的代碼實現(xiàn),你將掌握這一實用的技巧,為你的Web應(yīng)用增添交互的樂趣,需要的朋友可以參考下2024-03-03

