【无标题】

uniapp小程序接口请求封装

新建根目录utils / request.js

const baseURL = "https://www.bradenhan.tech"
const timeout = 5000

// 封装api请求
const request = function(option){ 
	// 获取用户传入的url
	var url = baseURL + option.url; 
	// 添加提请求头
	var  header = option.header||{}
	if(!!option.needToken){
		// 添加token 
		header.Authorization =  'Bearer ' +  uni.getStorageSync('token');  
	}
	// header.source=1;
	// header.channel="h5";
	
	// 加载提示
	var loading = option.loading;
	// 如果有loading就显示loading
	if(loading){
		uni.showLoading(loading)
	}
  
  // 返回一个promise
	return new Promise((resolve,reject)=>{  
		// 发起一个request请求
		uni.request({
			url, //请求url
			method:option.method||"GET", //请求方法
			header, //请求头
			timeout,
			data:option.data||option.params, //请求数据
			success(res){
				// 成功返回结果
				if(res.statusCode===200){
					resolve(res.data)
					// 如果是101 没有权限
					if(res.data.code==101){
						uni.showToast({
							title: res.data.msg,
							icon:'none'
						})
						uni.redirectTo({
							url: '/pages/login/index',
						})
					}
					if(res.data.code!=200&&res.data.code!=0){
						uni.showToast({
							icon:'none',
							title:res.data.msg||'请求错误'
						})
					}
				} 
			},
			fail(err){
				// 失败返回失败结果
				uni.showToast({
					title: '请求失败',
					icon:'error'
				})
				console.error(err);
				reject(err)
			},
			complete(){
				// 完成 关闭loading
				if(loading){
					uni.hideLoading()
				}
			}
		})
	})
}
// 定义get简洁方法
request.get=function(url,config){
	return  request({
		url,
		method:"GET",
		...config
	})
}
// 定义post简洁方法
request.post=function(url,data,config){
	return  request({
		url,
		method:"POST",		
		...config,
		data
	})
}
// 导出请求
export default request;

新建根目录 api / index.js (存放接口)

// @/api/index.js

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

// 用户注册
export function customUseRegister(data){
	return request.post("/xxxx1",data)
}

// 微信用户登录
export function customUserLogin(data){
	return request.post("/xxxx2",data)
} 

// 更新用户信息 -- 需要使用Token
export function customUserUpdate(data){
	return request.post("/xxxx3",data,{needToken: true})
}

示例 页面中使用:

import { customUserUpdate } from '@/api/index.js'
 let query = {
      data: 123
 }
 customUserUpdate(query).then(res => {
    console.log('===============', res);
 })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值