跳至主要內容

uniapp封装请求方式

周浚豪...大约 1 分钟uniapp请求封装

uniapp封装请求方式

1、在根目录中创建 utils 文件夹,并且在 utils 下继续创建 request.js 文件

2、在 request.js 中书写一下内容

//项目的配置文件
import config from "@/config/config.js"
//项目的状态管理工具,也可以使用vuex and uni.getStorageSync
import { useUser } from '@/store/index.js'
let store = useUser();

const request = ({
	url,
	method,
	data
}) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.BASE_URL + url,
			method,
			data,
			header: {
				'token': store.$state.userInfo.token,//后端要求的请求头
			},
			success: (res) => {
                //处理接口各种状态的地方,根据自己公司的接口规则进行修改
				switch (res.data.code) {
					case 500: //接口报错
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						break;
					case 355: //未登录、登录超时
						uni.navigateTo({
							url: '/pagesA/login/index'
						});
						break;
					case 200:
						resolve(res.data)
						break;
				}
			},
			fail: (err) => {
				console.log(err);
				uni.showToast({
					title: JSON.stringify(err),
					icon: 'none'
				})
			}
		});
	})
}

export default request;

3、在根目录中创建 config 文件夹,并且在 config 下继续创建 api.js 文件

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

//post
export let wxLogin = (data) => {
	return request({
		url: '/user/login/app/code',
		method: 'post',
		data
	})
}

//get
export let userInfo = (id) => {
	return request({
		url: '/user/' + id,
		method: 'get'
	})
}

4、在需要使用的地方引入

import { wxLogin } from "@/config/api.js"
    //一般请求后端接口都会出现异步的情况,自己抉择是否需要使用async解决异步
	const getphonenumber = async (e) => {
		await wxLogin({
			phoneCode: e.detail.code,
			code: code.value
		}).then(res => {
			userInfo.value = res.data
			console.log(userInfo.value);
			if (!res.data.nickname) close.value = true;
			else {
				uni.navigateBack({
					delta: 1
				});
			}
		})
	}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.8