AI智能
改变未来

axios记录

request.js

import axios from \'axios\'import { MessageBox } from \'element-ui\'import mutual from \'./parentMutual\'// 创建一个axios实例const instance = axios.create() // { timeout: 3000 }// 白名单(不加loading效果)let whiteList = [\'/logisticsTrackings\', // 快速查询以及运单轨迹详情\'/Payment/GetPaymentInfo\',//支付接口\'/scheduleJobs/importShipmentJob\'//异步导入]// http request 拦截器// let accesssToke = \'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IkJFQ0M4NUNBOTc1MDEyQTZERUMzNzk2MzczODBBN0ZGQUZGMjkzMEMiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJ2c3lGeXBkUUVxYmV3M2xqYzRDbl82X3lrd3cifQ.eyJuYmYiOjE1Mzk5MTk1NTUsImV4cCI6MTUzOTkyMzE1NSwiaXNzIjoiaHR0cHM6Ly9hdXRoLmdsb2JhbHBjZi5uZXQiLCJhdWQiOlsiaHR0cHM6Ly9hdXRoLmdsb2JhbHBjZi5uZXQvcmVzb3VyY2VzIiwidGVuYW50SWRlbnRpdHkiLCJmaWxlVXBsb2FkIiwidmF0Q2xpZW50IiwidHJhY2tpbmdZZWVTZXJ2aWNlIiwiUGxhdGZvcm1TaG9wIiwidHJhZGVNYXJrUmVnaXN0cmF0aW9uIl0sImNsaWVudF9pZCI6InNhYXMtanMtY2xpZW50Iiwic3ViIjoiODkxZGNmY2ItNjFmMi00NmNjLWEwNmYtMmZlZDMxN2NkMzE0IiwiYXV0aF90aW1lIjoxNTM5OTE1MzY3LCJpZHAiOiJsb2NhbCIsInByZWZlcnJlZF91c2VybmFtZSI6Imxlby5odWFuZ2xpYW5nMjAxNUBnbWFpbC5jb20iLCJ1bmlxdWVfbmFtZSI6Imxlby5odWFuZ2xpYW5nMjAxNUBnbWFpbC5jb20iLCJ0ZW5hbnRjb2RlIjoic2FhczAxIiwidGVuYW50bmFtZSI6IiIsImZ1bGxfbmFtZSI6IuS6ruWTpSIsInJvbGUiOiJUZW5hbnRPd25lciIsImVtYWlsIjoibGVvLmh1YW5nbGlhbmcyMDE1QGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJwaG9uZV9udW1iZXIiOiIxODMzMjU1NTQ4NCIsInBob25lX251bWJlcl92ZXJpZmllZCI6dHJ1ZSwic2NvcGUiOlsib3BlbmlkIiwicHJvZmlsZSIsInRlbmFudElkZW50aXR5IiwiZmlsZVVwbG9hZCIsInZhdENsaWVudCIsInRyYWNraW5nWWVlU2VydmljZSIsIlBsYXRmb3JtU2hvcCIsInRyYWRlTWFya1JlZ2lzdHJhdGlvbiJdLCJhbXIiOlsicHdkIl19.ZlbkEzBX_yZq0qoXFhBtbxRFNhXnQPhHSzjq_GSJs4z8txo2T0Z7Q-Wbz3rOJXOv7WrIOBvLOekbmfbkbBIrG8G_cHI5XrMXE8MPUFAD13dEOBpcJqQ5dIYZLkrTwHiSNXpA1_QN6HK46T8jcfDJvNFcApOiAI-a_9PWlqutIq7t2CUhdYYGLMtFMb91AwQ43B_5h2knWKj4clSuffh7TjiEwGaH55SchJyRFuAdxRLNSvmC5bAbMhfM9d6DWm1dL3ZIXqbQr0J54duIg397yRhXDZAPm9v7NAIoEn7Ghxi6ElnaoFXsLtvonIP5fXGR0-LTYn6MLjDT-KEx68lrEQ\'instance.interceptors.request.use(config => {let blackBool = true // 默认使用loading// loading 关闭mutual.loadingEnd()// 白名单不加loading效果for (var i = 0; i < whiteList.length; i++) {if (config.url.toLocaleLowerCase().indexOf(whiteList[i].toLocaleLowerCase()) != -1) {blackBool = falsebreak}}if (blackBool) {// loading 开始mutual.loadingStart()}if (!localStorage[\'accessToken\']) {// 没有用户标识  即需要用户去登陆if (window.parent.login401) {// 调用父级方法登录// console.log(window.parent)window.parent.login401()}} else {config.headers[\'authorization\'] = \'Bearer \' + localStorage[\'accessToken\']// 有用户标识 则将用户标识符设置为请求头}// config.headers[\'authorization\'] = accesssTokereturn config},error => {MessageBox.alert(error, \'接口请求错误\', {confirmButtonText: \'确定\'})if (error) {return Promise.reject(error)}})/*** http response 拦截器* resp.data.code:*    -10: 登录超时*    -1:登录无效*    0:成功,正常*    400:成功返回,需特殊处理*/instance.interceptors.response.use(resp => {mutual.loadingEnd()// 在这里对返回的数据进行处理if (resp.data.code === 403 || resp.data.code === 401) {// 后台返回登录超时   则置空缓存中的用户标识 并登录if (window.parent.login401) {// 调用父级方法登录// console.log(window.parent)mutual.login401()}} else if (resp.data.code === 500) {// 后台返回400console.log(\'接口报错了\')MessageBox.alert(\'接口请求错误,请联系管理员\', \'接口请求错误\', {confirmButtonText: \'确定\'})}return Promise.resolve(resp)},error => {mutual.loadingEnd()console.log(`err: ${error}`)console.log(\'code\', error.code)// for debugger//  1.判断请求超时if (error.code === \'ECONNABORTED\' && error.message.indexOf(\'timeout\') !== -1) {if (localStorage[\'timeoutUrl\']) {let arr = JSON.parse(localStorage[\'timeoutUrl\'])arr.push(error.config.url)let timeoutUrl = new Set(arr)localStorage[\'timeoutUrl\'] = JSON.stringify(timeoutUrl)} else {let arr = []arr.push(error.config.url)localStorage[\'timeoutUrl\'] = JSON.stringify(arr)}console.log(\'根据你设置的timeout请求超时 判断请求现在超时了,超时接口为:\' + localStorage[\'timeoutUrl\'])MessageBox.confirm(\'您访问当前页面超时,请联系管理员\', \'提示\', {confirmButtonText: \'确定\',cancelButtonText: \'取消\',type: \'warning\'}).then(() => {window.location.reload()}).catch(() => {window.location.reload()})// return axiosInstance.request(originalRequest);//例如再重复请求一次}if (error.response) {switch (error.response.status) {case 400:if (error.request.responseType === \'blob\') {var reader = new FileReader()reader.addEventListener(\'loadend\', function () {let Obj = JSON.parse(reader.result)MessageBox.alert(Obj.Errors[0].Message, \'错误提示\', {confirmButtonText: \'确定\'})})reader.readAsText(error.response.data, \'utf-8\')return}MessageBox.alert(error.response.data.Errors[0].Message, \'错误提示\', {confirmButtonText: \'确定\'})breakcase 401:if (window.parent.login401) {// 调用父级方法登录// console.log(window.parent)MessageBox.confirm(\'您当前没有访问当前页面的权限,请联系管理员\', \'提示\', {confirmButtonText: \'确定\',cancelButtonText: \'取消\',type: \'warning\'}).then(() => {mutual.login401() // 调用父级方法登录}).catch(() => {mutual.login401() // 调用父级方法登录})}breakcase 403:if (window.parent.login401) {// 调用父级方法登录// console.log(window.parent)MessageBox.confirm(\'您当前没有访问当前页面的权限,请联系管理员\', \'提示\', {confirmButtonText: \'确定\',cancelButtonText: \'取消\',type: \'warning\'}).then(() => {mutual.login401() // 调用父级方法登录}).catch(() => {mutual.login401() // 调用父级方法登录})}breakcase 404:// MessageBox.alert(\'接口请求错误,请联系管理员\', \'接口请求错误\', {//   confirmButtonText: \'确定\'// })mutual.login404()breakcase 500:// MessageBox.alert(\'接口请求错误,请联系管理员\', \'接口请求错误\', {//   confirmButtonText: \'确定\'// })// MessageBox.alert(error.response.data.Errors[0].Message, \'接口请求错误\', {//   confirmButtonText: \'确定\'// })console.log(error.response.data)window.parent.toError(error.response.data.Errors[0].Message)}}return Promise.reject(error)})export default instance
import axios from \'../../common/request.js\'const head = process.env.API_ROOTconst user = process.env.PREFERENCE_SERVICE//get方法export function importShipmentJob (jobId,params) {const url = head + `/scheduleJobs/importShipmentJob/${jobId}`return axios.get(url,{params}).then((res) => {return Promise.resolve(res.data)}).catch((err) => {return Promise.reject(err)})}//post方法export function getAllShipmentNoQuotaSearchTagsByCondition (params) {const url = head + `/shipments/allShipmentNoQuotaSearchTagsByCondition`return axios.post(url,params).then((res) => {return Promise.resolve(res.data)}).catch((err) => {return Promise.reject(err)})}//put方法export function batchShipmentTrackingStatus (trackingStatus,params) {const url = head + `/shipments/batchShipmentTrackingStatus/${trackingStatus}`return axios.put(url,params).then((res) => {return Promise.resolve(res.data)}).catch((err) => {return Promise.reject(err)})}//delete方法export function deleteimportShipmentJob (params) {let data = {data:params}const url = head + `/scheduleJobs/importShipmentJob`return axios.delete(url,data).then((res) => {return Promise.resolve(res.data)}).catch((err) => {return Promise.reject(err)})}// 导出表格,文件流export function exportExceptionShipmentFile (params) {const url = head + \'/shipments/exportExceptionShipmentFile\'return axios.post(url, params, {responseType: \'blob\'}).then((res) => {return Promise.resolve(res.data)}).catch((err) => {return Promise.reject(err)})}

使用

exportExceptionShipmentFile(params).then((res) => {// let fileName = res.headers[\'content-disposition\'].split(\';\')[1].split(\'=\')[1]let date = new Date()let dateName = this.utils.timeFormat(date, \'yyyy-MM-dd hh:mm:ss\')this.utils.Export(res, excelName + dateName + \'.xlsx\')})Export (data, fileName) { // 文件流下载const blob = new Blob([data])if (\'download\' in document.createElement(\'a\')) { // 非IE下载const elink = document.createElement(\'a\')elink.download = fileNameelink.style.display = \'none\'elink.href = URL.createObjectURL(blob)document.body.appendChild(elink)elink.click()URL.revokeObjectURL(elink.href) // 释放URL 对象document.body.removeChild(elink)} else { // IE10+下载navigator.msSaveBlob(blob, fileName)}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » axios记录