欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

uni-app封装request请求

程序员文章站 2022-06-17 22:39:07
config.js// export const baseURL = 'http://localhost:8081'// 小程序或app真机调试时使用export const baseURL = 'http://192.168.1.11:8081'request.jsimport { baseURL } from './config.js'export default function (options) { return new Promise((resolve, reject) =&...

config.js

// export const baseURL = 'http://localhost:8081'
// 小程序或app真机调试时使用
export const baseURL = 'http://电脑IP:8081'

获取电脑IP方法,控制台ipconfig

request.js

import { baseURL } from './config.js'

let ajaxTimes = 0

export default function(options) {
	ajaxTimes++
	uni.showLoading({
		title: '加载中...',
		mask: true
	})
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseURL + options.url,
			method: options.method || 'get',
			data: options.data || {},
			success: res => {
				resolve(res.data)
			},
			fail: err => {
				reject(err)
			},
			complete: () => {
				ajaxTimes--
				if (ajaxTimes === 0) {
					uni.hideLoading()
				}
			}
		})
	})
}

base.js

//用户user
export const USER_PATH = '/interest/user/public'
...

user.js

import request from './request.js'
import { USER_PATH } from './base'

export const registered = (data) => {
	//注册
	return request({
		url: USER_PATH + '/registered',
		method: 'POST',
		data
	})
}

export const getCode = (mobilePhone) => {
	//获取手机验证码
	return request({
		url: USER_PATH + '/code',
		data: {
			mobilePhone
		}
	})
}

export const getToken = (mobilePhone, code) => {
	//登录获取token
	let data = {
		mobilePhone,
		code,
	};
	return request({
		url: USER_PATH + '/token',
		data: data
	})
}

main.js全局注册

import * as USER from '@/request/user.js'
Vue.prototype.$USER = USER

person.vue 发送请求

async handleClickLogin() {
	// 登录
	if (this.mobilePhone.trimLeft() == '' || this.valCode.trimLeft() == '') {
		showToast('请先输入有效的手机号以及验证码')
		return
	}
	const result = await this.$USER.getToken(this.mobilePhone, this.valCode)
	// console.log(result.data)
	if (result.status == 2000) {
		this.count = 0
		uni.setStorageSync("token", result.data.token)
		uni.setStorageSync("mobilePhone", result.data.mobilephone)
		uni.setStorageSync("id", result.data.id)
	}
}

本文地址:https://blog.csdn.net/weixin_45585996/article/details/107963236

相关标签: uni-app uniapp