uniapp的request.js请求方法封装

1,286 阅读1分钟

一、封装要点

  • 公共请求前缀baseUrl定义(可以放在专门的配置文件里)
  • 公共请求头token设置
  • 参照axios支持params参数,用来将参数&符拼接
  • 使用扩展符支持自定义请求头

注意:在微信小程序中 wx.showLoading 和 wx.showToast 同时只能显示一个,所以我这里等待hideLoading成功后异步showToast。 image.png

二、用promise封装

// utils/request.js

const baseUrl = "https://xxx/xxx"

function request(options) {
	uni.showLoading({
		title: "加载中",
		mask: true,
	});
	let defaultHeader = {
		'glens_token': uni.getStorageSync('token')
	}
	// 如果使用params传参则,以&符拼接的格式传参
	if (options.params) {
		options.data = options.params
		defaultHeader['Content-Type'] = 'application/x-www-form-urlencoded'
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + options.url, // 接口地址:前缀+方法中传入的地址
			method: options.method || 'GET', // 请求方法:传入的方法或者默认是“GET”
			data: options.data || {}, // 传递参数:传入的参数或者默认传递空集合
			header: {
				...defaultHeader,
				...options.header
			},
			success: (res) => {
				if (res.statusCode && res.statusCode != 200) {
					uni.hideLoading().then(() => {
						uni.showToast({
							title: "api错误" + res.errMsg,
							icon: 'none'
						});
					})
					reject()
				} else {
					res = res.data
					if (res.code == 200) {
						uni.hideLoading()
						resolve(res.data)
					} else {
						uni.hideLoading().then(() => {
							uni.showToast({
								title: res.message,
								icon: 'none'
							});
						})
						reject(res.message)
					}
				}
			},
			// 这里的接口请求,如果出现问题就输出接口请求失败
			fail: (err) => {
				uni.hideLoading().then(() => {
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
				reject(err)
			}
		})
	})
}

export default request

三、使用

// utils/api/user.js

import request from '../http.js'

export const login = (params) => request({
	url: '/e-module/sys/app/auth/login',
	method: 'POST',
	params
})
import * as userApi from '@/utils/api/user.js'

userApi.login(this.formData).then(res => {
    // do somethings
})