uniapp封装请求拦截和响应拦截的方法

单独对发送网络请求接口--- uni.request  的封装

请求文件的封装  resquest.js

建立resquest请求文件 resquest.js

var baseURL = '/' //公共api地址。

export default (options) => {
    // 这里网络可以做请求之前的操作,比如
       挂载token,放置loading等
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseURL + options.url, //接口地址:前缀+方法中传入的地址
			method: options.method || 'GET', //请求方法:传入的方法或者默认是“GET”
			data: options.data || {}, //传递参数:传入的参数或者默认传递空集合
			dataType: options.dataType || 'application/x-www-form-urlencoded;charset=utf-8',
			timeout: options.dataType || 10 * 1000, //接口请求超时时间设置
			header: {
				'Authorization': '',
				'X-AUTH-CLIENT': '',
				'content-type': options.headers['Content-Type'] ||
					'application/x-www-form-urlencoded;charset=UTF-8'
			},
			success(res) {
				resolve(res.data);
			},
			fail(err) {
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
};

在封装接口的api文件下的modules下的auth.js文件中,引入request文件并传入接口所需参数

import Request from "../../utils/request.js"
import Qs from 'qs'

//接口名称
export function getAuth(data) {
  return Request({
    url: '/online-auth/ali/mini/user/oauth',
    method: 'POST',
    data:data,
	// headers不做配置时,默认为application/x-www-form-urlencoded;charset=UTF-8
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'  
	}
  })
}

把api下的module文件下的所有js文件在index.js文件中 引入并统一用变量Api接收进行导出

import * as publicapi from './module/public'
import * as ali from './module/ali'
import * as weixin from './module/weixin'
const Api = Object.assign({},publicapi,ali,weixin)
export default Api

最后在main.js的入口文件中导入Api并全局挂载

//接口api挂载到全局,使用时:this.Api.getAuth()//getAuth为方法名
import Api from './api'
Vue.prototype.$Api = Api

封装请求响应拦截器

(和上面只对uni.request的封装不一样)

  • 新建一个request.js文件,默认导出一个对象,对象中封装请求拦截响应拦截以及request请求
export default {
  config: {
    baseURL: '',
    // 请求拦截器
    beforeRequest() {},
    // 响应拦截器
    handleResponse() {}
  },
  // request 请求
  request() {}
}
  •  在请求拦截器中封装公共方法 - 这里进行拦截测试
export default {
  config: {
    baseURL: baseURL,
    // 请求拦截器
    beforeRequest() {
      return new Promise((resolve, reject) => {
        console.log('请求拦截器') resolve('123456')
      })
    },
    // 响应拦截器
    handleResponse() {}
  },
  // request 请求
  request() {
    return this.config.beforeRequest().then(opt => {
      console.log(opt)
    })
  }
}
  • 在页面导入request.js文件 - 这里可以看到正常执行成功

import api from '../../utils/request.js

onShow() {
	api.request() 
    // 可以看到成功打印出来 请求拦截器和123456 ,然后就可以将公共的的方法封装在请求拦截器中
}

 这里贴上完整的request.js请求响应拦截的代码

export default {
	config: {
		baseURL: 'https://www...',
		// 请求拦截器
		beforeRequest(options = {}) {
			return new Promise((resolve, reject) => {
				options.url = this.baseURL + options.url;
				options.method = options.method || 'GET';
				options.data = options.data;
				// options.responseType = 'arraybuffer'
				// 封装自己的请求头
				options.header = {
					token: '123'
				}
				console.log(options, 'options')
				resolve(options)
			})
		},
		// 响应拦截器
		handleResponse(data) {
			return new Promise((resolve, reject) => {
				const [err, res] = data;
				// // 处理错误
				// if (res && res.statusCode !== 200) {
				// 	let msg = res.data.msg || '请求错误';
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: msg
				// 	}) return reject(msg);
				// }
				// if (err) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '请求错误'
				// 	}) return reject(err);
				// }
				console.log(data, res.statusCode, 'datata')
				// if (res.statusCode == 200) {
				// 	uni.showToast();
				// 	// uni.showToast('数据加载失败');
				return resolve(res.data)
				// }
			})
		},
	},
	// request 请求
    // 下面最主要的一段代码,利用了promise的特性,当调用request方法时,先经过
请求拦截可以拿到请求参数,在请求之前做处理,请求函数会把处理之后的参数作为结果抛出
给了uni.request进行请求,uni.request执行完再次return了promise,接着执行响应
拦截.then中的 response函数,response函数接收到uni请求响应的结果作为res传递给
响应拦截(这里为什么能拿到uni的响应结果因为uni返回的也是promise),在response
就可以对响应的数据处理后再进行promise的返回
	request(options = {}) {
		return this.config.beforeRequest(options).then(opt => {
			return uni.request(opt)
		}).then(res => this.config.handleResponse(res))
	}
}

 对封装好的请求进行使用

封装api请求方法

import api from "../../utils/request.js"

export function pubdemo(data) {
    return api.request({
        url: '/api/fa/fdsa/fda/',
        method: 'post',
        data: data,
    })
}

此文借鉴了这篇文章的同时加了自己的理解,贴出来可同时查阅。

uniapp封装请求拦截器(封装请求拦截和响应拦截的方法)-老汤博客首先我们先看一下uni官方给开发者提供的uni.request用来网络请求的apiuni.request可以看到我们每次请求数据的时候都需要按照这个格式来请求,这样会使代码冗余并且难以维护,所以就需要将uni.request进行二次封装。https://tangjiusheng.com/web/qdkf/669.html


 最后贴一个 uni-app请求包,可直接调用请求响应拦截。uni.$http.get('/api/public/v1/home/catitems').then()

npm i @escook/request-miniprogram

import { $http } from '@escook/request-miniprogram'
uni.$http = $http

$http.baseUrl = 'https://www....com'

$http.beforeRequest = function(options) {return options}

$http.afterRequest = function(response) {}

也可像下面一样进行封装调用

  • 10
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值