uniapp 请求封装

 1.创建request.js文件

export default {
	config: {
		baseUrl: "http://192.168.1.1:0000", // 示例
		header: {
			'Content-Type': 'application/json;charset=UTF-8'
			// 'Content-Type': 'application/x-www-form-urlencoded', 
		},
		data: {},
		method: "GET",
		dataType: "json",
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	// 请求拦截器
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		// 基于 Promise 的网络请求
		return new Promise((resolve, reject) => {
			uni.showLoading()
			let _config = null
			options.complete = (response) => {
				uni.hideLoading()
				// console.log(response, 'response.data',this);
				let {
					code,
					info
				} = response.data
				if (info == "登录信息过期") {
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login'
						})
					}, 1500)
				}
				if (code === 400) {
					uni.showToast({
						title: info,
						icon: "none",
						position: "center",
						duration: 2000
					})
					// reject(response)
				} else if (code === 200) {
					uni.showToast({
						title: info,
						icon: "none",
						position: "center",
						duration: 2000
					})
					resolve(response.data)
				} else if (code === 500) {
					uni.showToast({
						title: info,
						icon: "none",
						position: "center",
						duration: 2000
					})
					resolve(response.data)
				} else {
					resolve(response.data)
				}
			}
			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			uni.request(_config);
		});
	},
	// url 为请求路径 data 为需要传递的值 options 进行封装
	// get请求
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	// post请求
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	// put请求
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
}

2.在main.js中引入

import api from './request.js'

Vue.prototype.$http = api

3.页面请求接口

async queryName() {
				const data = {
					name:''
				}
				const res = await this.$http.post("接口地址", data)
				console.log(res, 'res');
			},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值