uniapp+axios请求的封装

uniapp+axios请求的封装

因在用vue3.0时会导致无法引有buildFullPath和settle两个库。所简单处理这两个方法

// utils/request.ts文件代码如下

javascript 复制代码
/***
 uniapp+axios请求的封装
**/

import axios from 'axios'
import $config from "@/config/config"
import {getToken,removeToken} from "@/utils/auth"

// create an axios instance
//创建axios实例
const service = axios.create({
	baseURL: process.env.NODE_ENV === 'development' ? $config.baseUrl.dev : $config.baseUrl.pro,
	withCredentials: true, // send cookies when cross-domain requests
	timeout: $config.timeout,// request timeout
	headers:{
		'Content-Type':'application/json;charset=utf-8'
	}
})


//响应请求
service.interceptors.request.use(
	config => {
		if (config.headers.auth) { // 判断请求是否需要认证
			if(getToken()) config.headers['Authorization'] ='Authorization '+getToken();
		}
		return config
	},
	error => {
		return Promise.reject(error)
	}
)

//响应拦截器
service.interceptors.response.use(({config,data}) => {
	  console.log(data)
		if (data.code === 'A0230') { // token过期
			if(getToken()){
				uni.showToast({
					icon:"loading",
					title: '会话已过期,重新获取',
					success() {
						 removeToken() //删除Token
						 console.log('失败处理')
					}
				})
			}
		}
	  
	},error => {
		const {code,msg} = error.response.data
		if (code === 'A0230') { // token过期
		 if(getToken()){
		 	uni.showToast({
		 		icon:"loading",
		 		title: '会话已过期,重新获取',
		 		success() {
		 			removeToken() //删除Token
					console.log('失败处理')
		 		}
		 	})
		 }
		} else {
			uni.showToast({
				title: msg,
				icon: 'none'
			});
			return Promise.reject(new Error(msg || 'Errors'))
		}
	}
)

//自己定义个适配器,用来适配uniapp的语法
service.defaults.adapter = function(config) {
	 return new Promise((resolve, reject) => {
			//if(typeof config.data==="string") data=JSON.parse(config.data) //TODO GET会变成string
			uni.request({
				method: config.method.toUpperCase(),
				url: combineURLs(buildFullPath(config.baseURL,config.url), config.params, config.paramsSerializer),
				header: {...config.headers},
				data:config.data,
				complete:(response)=>{
					response = {
					  data: response.data,
					  status: response.statusCode,
					  errMsg: response.errMsg,
					  header: response.header,
					  config: config.data
					};
				 settle(resolve, reject, response);
				}
			})
	    })
}






function buildFullPath(baseURL, requestedURL) {
  console.log(buildURL(requestedURL));
  if (baseURL && !buildURL(requestedURL)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
}
 
function buildURL(url) {
  // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  // by any combination of letters, digits, plus, period, or hyphen.
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
 
function combineURLs(baseURL, relativeURL) {
  return relativeURL
    ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
    : baseURL;
}

function settle(resolve, reject, response) {
  let validateStatus = response.config.validateStatus;
  if (!response.status || !validateStatus || validateStatus(response.status)) {
    resolve(response);
  } else {
    reject(createError(
      'Request failed with status code ' + response.status,
      response.config,
      null,
      response.request,
      response
    ));
  }
};
 


export default service

使用封装的例子

//aip/auth.ts

javascript 复制代码
/**
 * 用户
 **/
import request from '@/utils/request'

/**
 * 反馈信息
 * @param {*} type 
 * @param {*} contact_mobile 
 * @param {*} content 
 * @param {*} images 
 */
export function getBanner(data)  {
	return request({
		url:`/index/banner`,
		method: 'POST',
		data:data,
		headers: {
			 'auth': true// 需要认证,通过
		}
	})
}
相关推荐
叫我菜菜就好10 分钟前
【Flutter_Web】Flutter编译Web第三篇(网络请求篇):dio如何改造方法,变成web之后数据如何处理
前端·网络·flutter
NoneCoder16 分钟前
CSS系列(26)-- 动画性能优化详解
前端·css·性能优化
滚雪球~16 分钟前
@vue/cli启动异常:ENOENT: no such file or directory, scandir
前端·javascript·vue.js
GDAL26 分钟前
vue3入门教程:ref函数
前端·vue.js·elementui
GISer_Jing35 分钟前
Vue3状态管理——Pinia
前端·javascript·vue.js
好开心331 小时前
axios的使用
开发语言·前端·javascript·前端框架·html
Domain-zhuo1 小时前
Git常用命令
前端·git·gitee·github·gitea·gitcode
菜根Sec1 小时前
XSS跨站脚本攻击漏洞练习
前端·xss
m0_748257182 小时前
Spring Boot FileUpLoad and Interceptor(文件上传和拦截器,Web入门知识)
前端·spring boot·后端
桃园码工2 小时前
15_HTML5 表单属性 --[HTML5 API 学习之旅]
前端·html5·表单属性