uni-app request请求封装

首先创建一个common文件,文件中写一个request.js
在这里插入图片描述
话不多说直接上代码


export  default {
	// 全局配置
	common:{
		baseUrl: "http://ceshi.dishait.cn",
		header:{
			"Content-type" : "application/json;charset=UTF-8"
		},
		data:{},
		method:"GET",
		dataType:'json'
	},
	// 请求返回  promise
	request(options={}){
		let common = this.common;
		// 组织参数
		options.url = common.baseUrl + options.url;
		options.header = options.header  || common.header;
		options.data = options.data  || common.data;
		options.method = options.method || common.method;
		options.dataType = options.dataType || common.dataType;
		
		// 请求
		return new Promise((res,rej)=>{
			uni.request({
				...options,
				success(result){
					let {statusCode,data}  = result;
					
					// 返回原始数据
					if(options.native){
						return res(result)
					}
					// 服务端失败
					if(statusCode !== 200 ){
						if(options.toast !== false){
							uni.showToast({
								title:data.msg  || "服务端失败",
								icon:"none"
							})
						}
						return rej(data)
					}
					
					res(data)
				},
				fail({errMsg}) {
					uni.showToast({
						title:errMsg  || "请求失败",
						icon:"none"
					})
					return rej()
				}
			})
		})
		
	},
	
	// get请求
	get(url,data={},options={}){
		options.url = url;
		options.data = data;
		options.method = 'GET';
		return this.request(options)
	},
	
	
	// post请求
	post(url,data={},options={}){
		options.url = url;
		options.data = data;
		options.method = 'POST';
		return this.request(options)
	},
	
	
	// delete请求
	delete(url,data={},options={}){
		options.url = url;
		options.data = data;
		options.method = 'DELETE';
		return this.request(options)
	}
	
}

然后在main.js引入

import Vue from 'vue'
import App from './App'
//引入request
import request from '@/common/request.js'
Vue.config.productionTip = false

App.mpType = 'app'
//挂载到vue的原型上
Vue.prototype.$http = request
const app = new Vue({
	...App
})
app.$mount()

组件中使用

mounted() {
			this.$http.get("/app_index").then(res => {
				this.swiperImages = res.swiperImages
				
			})
		}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值