uniapp request 请求封装 复制可用

先建立一个文件夹 common 在根目录下

建立一个ajax.js文件 文件代码

我这里把token存在vuex里了 所以引用了vuex 不需要的话可以删掉 

import Vue from 'vue'
import {
	store
} from '../../store/index.js';

function ToastError(d) {
	uni.showToast({
		icon: 'none',
		title: d.msg || d.message || '未知错误'
	})
}

export default function http(url, data, method = 'GET', showError = true) {
	const state = Vue.prototype.$store.state; 
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${Vue.prototype.$baseURL}${url}`,
			method,
			data: data,
			
			header: {
				'X-Csrf-Token': state.token 
			},
			success(res) { 
				console.log(res)

				if (正确的code) {
					resolve(resData.data);
					// http status 200 && data.code 444 为登录失效 或 未登录
				}else {
					uni.hideLoading()
					showError && ToastError(res.data);
					reject(res);
				}
			},
			fail(e = {}) {
				console.log(e);
				if (e.errMsg && e.errMsg.startsWith('request:fail ')) {
					e.msg = '网络错误'
				}
				showError && ToastError(e);
				reject(e);
			}
		});
	});
}

建立一个api.js文件  引入刚才的ajax.js

这里面有get和post请求的实例

import ajax from './ajax.js';


export function test(phone) {
	return http(`/test/${phone}`);
}

// 登录接口
export function test(body) {
	return http('/test', body, 'POST');
}

在main.js挂载一下请求地址

Vue.prototype.$baseURL = "https://12345";

在页面的时候先引入api.js 里面需要请求的接口 就可以在页面里使用了

import {
		test
		
	} from '../../public/lib/api.js'
test(body).then((res) => {
					console.log(res)
				}).catch((res)=>{
console.log(res)
});

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值