当前位置: 代码网 > it编程>编程语言>Javascript > JavaScript中如何校验接口是否重复提交

JavaScript中如何校验接口是否重复提交

2024年05月18日 Javascript 我要评论
js校验接口重复提交示例代码request.jsimport axios from 'axios'import { notification, messagebox, message, loading

js校验接口重复提交

示例代码

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'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseurl选项,表示请求url公共部分
  baseurl: process.env.vue_app_base_api,
  // 超时
  timeout: 10000
})
 
//     请求拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const istoken = (config.headers || {}).istoken === false
  // 是否需要防止数据重复提交
  const isrepeatsubmit = (config.headers || {}).repeatsubmit === false
  if (gettoken() && !istoken) {
    config.headers['authorization'] = 'bearer ' + gettoken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  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; // 请求数据大小
    const limitsize = 5 * 1024 * 1024; // 限制存放数据5m
    if (requestsize >= limitsize) {
      console.warn(`[${config.url}]: ` + '请求数据大小超出允许的5m限制,无法进行防重复提交验证。')
      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;                // 请求数据
      const s_time = sessionobj.time;                // 请求时间
      const interval = 1000;                         // 间隔时间(ms),小于此时间视为重复提交
      //此处校验是否是重复提交
      if (s_data === requestobj.data && requestobj.time - s_time < interval && s_url === requestobj.url) {
        const message = '数据正在处理,请勿重复提交';
        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)
})
 
// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorcode[code] || res.data.msg || errorcode['default']
    // 二进制数据则直接返回
    if (res.request.responsetype ===  'blob' || res.request.responsetype ===  'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      if (!isrelogin.show) {
        isrelogin.show = true;
      //   messagebox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', { 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 = "系统接口请求超时";
    } else if (message.includes("request failed with status code")) {
      message = "系统接口" + 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: "正在下载数据,请稍候", 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('下载文件出现错误,请联系管理员!')
    downloadloadinginstance.close();
  })
}
 
export default service

方法补充

除了上文的方法,小编还为大家整理了一些其他javascript接口防重复提交的方法,希望对大家有所帮助

方法一:js防止重复提交接口

思路:定义一个事件的标识变量为false,点击事件里先判断变量是否为true,是的话就不执行,否者的话把变量改为true,之后再执行点击事件内容即可。

下方代码表示只执行一次

let isflag= false;
//点击事件
$(document).on("click","#_submit",function (){
    if (isflag) {
        return false;
    }
    isflag= true;
    
    //执行内容。。。。。
})

方法二:防止重复点击

定义一个clickthrottle.js文件

/* 防止重复点击 */
let clicktimer = 0

function clickthrottle(interval = 3000) {
    let now = +new date(); // 获取当前时间的时间戳
    let timer = clicktimer; // 记录触发事件的事件戳
	
    if (now - timer < interval) {
    	// 如果当前时间 - 触发事件时的事件 < interval,那么不符合条件,直接return false,
    	// 不让当前事件继续执行下去
        return false;
    } else { 
    	// 反之,记录符合条件触发了事件的时间戳,并 return true,使事件继续往下执行
        clicktimer = now;
        return true;
    }
}

export default clickthrottle

+new date()这个代码是获得当前时间的时间戳,与 new date().gettime() 、 new date().valueof() 以及 date.now() 是一样的。

方法三:两种防止js重复执行的方法

其一:

 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);
//回调函数启用按钮
$('button').prop('disabled',false);
如果想要最后一次点击生效,把timer定时器放在函数外每次调用进行检测;如果不涉及定时器,就在函数内部把函数赋值给自己让每次调用都执行新的逻辑
 
var timer;
var foo = function() {
    timer && cleartimeout(timer);
    timer = settimeout(function() {
        console.log(0);
    }, 5000);
    //something
}

到此这篇关于javascript中如何校验接口是否重复提交的文章就介绍到这了,更多相关javascript接口重复提交内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com