首页 > 其他分享 >web 通用 request - download

web 通用 request - download

时间:2023-08-18 14:11:32浏览次数:49  
标签:web code return request error download config response

request

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, getzyToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    let token = config.url.indexOf('zyapi') > -1 ? getzyToken() : getToken()
    if (config.url.indexOf('zyapi') > -1) {
      config.baseURL = process.env.VUE_APP_BASE_API + 'mz'
      config.url = config.url.split('zyapi')[1]
    } else {
      config.baseURL = process.env.VUE_APP_BASE_API
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      config.params = {
        ...config.params,
        token: config.params?.token || token,
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  },
)

// response interceptor 响应拦截
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (response.config.responseType === 'blob') return response
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== '0') {
      const [code, message] = res.message?.split(':')

      Message({
        message: message || 'Error',
        type: 'error',
        duration: 5 * 1000,
        showClose: true,
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (code === 'AUTHORITY-USER-INFO-ERROR-01') {
        // to re-login
        MessageBox.confirm('您已注销,可以留在此页,或重新登录', '确认注销', {
          confirmButtonText: '重新登录',
          cancelButtonText: '留在此页',
          type: 'warning',
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.body
    }
  },
  error => {
    console.log('err' + error) // for debug
    //code ==5 token失效重新登陆
    if (error.response.data.code === '5') {
      MessageBox.confirm('用户登陆信息不存在或已失效,请重新登陆', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        store.dispatch('user/resetToken')
      })
      return Promise.reject(error)
    }
    //code ==5 token没有
    if (error.response.data.code === '4') {
      MessageBox.confirm('您已注销,可以留在此页,或重新登录', '确认注销', {
        confirmButtonText: '重新登录',
        cancelButtonText: '留在此页',
        type: 'warning',
      }).then(() => {
        store.dispatch('user/resetToken')
      })
      return Promise.reject(error)
    }

    Message({
      message: [
        'timeout of 5000ms exceeded',
        'Network Error',
        'Request failed with status code 404',
      ].includes(error.message)
        ? '网络错误,请稍后再试'
        : error.message == 'Request failed with status code 400'
        ? error.response.data.message || '请求参数错误' //'请求参数错误'
        : error.message,
      type: 'error',
      duration: 8 * 1000,
      showClose: true,
    })
    return Promise.reject(error)
  },
)

export default service

文件下载

import request from './request'

export default function (config) {
  return request({
    ...config,
    responseType: 'blob',
  }).then(({ data, headers }) => {
    let filename = ''
    if (config.name) {
      filename = config.name
    } else {
      if (headers['content-disposition']) {
        filename = headers['content-disposition'].match(
          /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
        )[1]
      } else {
        filename = decodeURIComponent(headers.attachment)
      }
    }

    downloadFile(filename, data)
  })
}

function downloadFile(fileName, content) {
  const blob = new Blob([content])
  if ('msSaveOrOpenBlob' in window.navigator) {
    window.navigator.msSaveOrOpenBlob(blob, fileName)
  } else {
    const a = document.createElement('a')
    a.download = fileName
    a.href = URL.createObjectURL(blob)
    a.click()
    URL.revokeObjectURL(blob)
  }
}

标签:web,code,return,request,error,download,config,response
From: https://www.cnblogs.com/sclweb/p/17640331.html

相关文章

  • 钉钉机器人监控项目异常_JavaWeb实现
    在prod环境,项目所触发的运行时异常,developer往往无法第一时间得知讯息(在没有项目监控的前提下),为了解决这一问题,可以利用钉钉机器人监控项目异常,实时通知/警报给developer。1>自定义紧急异常EmergencyException2>在重要业务中产生的异常转换为此异常3>在全局异常捕获,针对此......
  • 文字转语音 - 搭建微软tts整合web服务提供api接口(免费)
     微软tts是业界公认文字转语音效果最佳本文使用docker搭建微软tts服务并提供api接口对外提供服务对接官方免费在线体验接口,搭建后可免费进行调用使用,不保证永久稳定可用调用方式url:http://127.0.0.1:5003/ttsmethod:POST参数 类型 描述text string 语音文字内容voiceName stri......
  • SpringMVC-1-解密Spring MVC:构建优雅、灵活的Web应用的秘诀
    今日目标能够编写SpringMVC入门案例了解SpringMVC原理1.SpringMVC介绍1.1SpringMVC概述思考:SpringMVC框架有什么优点?SpringMVC是一种基于Java实现MVC模型的轻量级Web框架优点使用简单,开发便捷(相比于Servlet)天然的与Spring框架集成(如IOC容器、AOP等)请求处理简化:支......
  • WebView2在WPF中的应用
    开发环境运行环境:.Net6开发环境:VisualStudio202217.1.3框架语言:WPF安装WebView2通过PackageManager控制台安装Install-PackageMicrosoft.Web.WebView2通过Nuget包管理器安装在窗体中添加名字空间:xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;asse......
  • web播放本地流视频
    <template><div><divclass="video"><video></video></div></div></template><script>exportdefault{mounted(){this.playVideo()},methods:{playVideo(......
  • 直播系统源码协议探索篇(二):网络套接字协议WebSocket
     上一篇我们分析了直播平台的会话初始化协议SIP,他关乎着直播平台的实时通信和多方互动技术的实现,今天我们来讲另一个协议,叫网络套接字协议WebSocket,WebSocket基于TCP在客户端与服务器建立双向通信的网络协议,并且可以通过单个长连接实现。在直播系统源码平台已经成为人们获取知识......
  • 直播系统源码协议探索篇(二):网络套接字协议WebSocket
    上一篇我们分析了直播平台的会话初始化协议SIP,他关乎着直播平台的实时通信和多方互动技术的实现,今天我们来讲另一个协议,叫网络套接字协议WebSocket,WebSocket基于TCP在客户端与服务器建立双向通信的网络协议,并且可以通过单个长连接实现。在直播系统源码平台已经成为人们获取知识、放......
  • 【Web开发指南】MyEclipse XML编辑器的高级功能简介
    1.在MyEclipse中编辑XML本文档介绍MyEclipse XML编辑器中的一些可用的函数,MyEclipse XML编辑器包括高级XML编辑,例如:语法高亮显示标签和属性内容辅助实时验证(当您输入时)文档内容的源(Source)视图、设计(Design)视图和大纲(Outline)视图文档格式内容辅助模板2.编辑模式使用MyEclipse......
  • 【Web开发指南】MyEclipse XML编辑器的高级功能简介
    MyEclipsev2023.1.2离线版下载1.在MyEclipse中编辑XML本文档介绍MyEclipse XML编辑器中的一些可用的函数,MyEclipse XML编辑器包括高级XML编辑,例如:语法高亮显示标签和属性内容辅助实时验证(当您输入时)文档内容的源(Source)视图、设计(Design)视图和大纲(Outline)视图文档格......
  • QtWebChannel和JavaScript进行通信(简单理解)
    说明在使用Qt(C++)和JavaScript之间实现通信时,通常会使用一些模块和技术来使两者能够交互和传递数据。这种通信通常用于在Qt应用程序中嵌入Web内容,或者在Web页面中嵌入Qt应用程序。以下是一些常用的模块和技术,以及它们的作用QtWebEngine模块:作用:QtWebEngine是Qt中的Web引擎,允......