uniapp 封装请求

第一步新建 utils 文件夹内的 request.js

const baseUrl = '请求路径';


/* token  登录标识 */
let token = "";
/* 判断机型  因为后台会通过机型不一样,所使用的登录参数也不一样*/
let channel = ''
// #ifdef APP-PLUS
channel = 'app';
// #endif
// #ifdef MP-WEIXIN
channel = 'weixin';
// #endif
// #ifdef H5
channel = 'h5';
// #endif

const httpRequest = (url, data, method) => {
	let userInfo = uni.getStorageSync('userInfo');
	console.log(userInfo)
	let obj ={
		...data,
		token:userInfo.token,
	}
	let httpDefaultOpts = {
		url: baseUrl + url,
		data: obj,
		method: method,
		header: {
			'Content-type': 'application/x-www-form-urlencoded',
			'content-type': 'application/json',
			"Accept": 'application/json',
		},
	}
	// resolve 是成功后的返回 在.then()里面    reject 是失败时候的返回  在  error 里面
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				console.log(res)
				console.log(res[1].statusCode)
				//后台返回错误信息  直接弹框  
				if (res[1].statusCode != 200) {
					uni.showModal({
						title: '提示',
						showCancel: false,
						content: res[1].data.message,
						success: function(res) {
							if (res.confirm) {}
						}
					});
				}
				//后台返回说 需要登录  直接跳登录页面
				if (res[1].data.code < 0) {
					uni.navigateTo({
						url:"/pages/login/index"
					})
				}
				resolve(res[1].data)
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};


export default {
	baseUrl,
	httpRequest,
}

第二步新建 utils 文件夹内的 http.js

import request from '@/utils/request'
/*   首页类别对应的商品*/
function homeCate(data) {
	let url = 'ys.Index/homeCate'
	let method = "POST"
	return request.httpRequest(url, data, method);
}

export default {
	homeCate,
}

第三步挂载 http.js 前往main.js main是程序的口所有的加载都是通过这个js开始的

import Vue from 'vue'
import App from './App'
import uView from "uview-ui";
Vue.use(uView);


/*挂载的主要代码*/
import http from './utils/http.js'
Vue.prototype.$http = http
/*挂在代码完毕*/


Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()

第四步 调用

<script>
	export default {
		data() {
			return {
			}
		},
		onLoad() {
			this.homeCateList()
		},
		methods: {
			/* 首页类别对应的商品 */
			homeCateList() {
				/*这里传入你想传入的参数值*/
				let data = {
					
				}
				this.$http.homeCate(data).then(res => {
					console.log('请求成功', res)
				}, error => {
					console.log(error)
				})
			},
		}
	}
</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值