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

uni-app封装ajax请求方法

程序员文章站 2022-03-07 13:43:24
uni-app封装ajax请求方法...

位置项目根目录index.js

定义了两种请求get和post

import baseconfig from "./common/baseconfig.js"

const httpClient = {
	request:function(method,url,data){
		var headers={
			"Content-Type": "application/x-www-form-urlencoded",
			"Auth-Token": uni.getStorageSync("auth_token")
		};
		
		return new Promise((resolve,reject)=>{
			uni.showLoading({
				title:"加载中",
				mask:true
			});
			
			uni.request({
				url:url,
				header:headers,
				data:data,
				method:method,
				dataType: 'json',
				success:function(res){
					uni.hideLoading()
					console.log("接口获取原始数据:-------------------",res.data)
					if(res.statusCode == 401){
						uni.showToast({
							icon: 'none',
							duration:1000,
							title: res.data.error.message
						});
						setTimeout(function(){
							uni.reLaunch({
								url: '../login/login'
							});
						},1500);
					}else{
						if(res.data.error != null){
							uni.showToast({
								icon: 'none',
								duration:1000,
								title: res.data.error.message
							});
							return;
						}else{
							resolve(res.data);
						}
					}
				},
				fail: function(err){
					uni.hideLoading()
					reject(err)
				}
			})
		})
	},
	Get: function(url,data){
		let allurl = this.geturl(url);
		return this.request('GET',allurl,data)
	},
	Post: function(url,data){
		let allurl = this.geturl(url);
		return this.request('POST',allurl,data)
	},
	geturl:function(url){
		return baseconfig.server+url
	}
};

module.exports = httpClient
位置common/baseconfig.js
var baseconfig={};

if(process.env.NODE_ENV === 'development'){
	baseconfig = {
		server:'http://development.test.net'
	}
}else if(process.env.NODE_ENV === 'production'){
	baseconfig = {
		server:'http://production.test.net'
	}
}

export default baseconfig;

根目录api.js

此js方法注册到全局vuex

import httpClient from './index.js'

export function get(url,params){
	return httpClient.Get(url,params)
};
export function post(url,params){
	return httpClient.Post(url,params)
};

根目录main.js修改

import {get,post} from ‘./api.js’
Vue.prototype.apiget = get
Vue.prototype.apipost = post
注册后在vue文件可以this.apiget直接调用

import Vue from 'vue'
import App from './App'

import store from './store'

import {get,post} from './api.js'
Vue.prototype.apiget = get
Vue.prototype.apipost = post

Vue.config.productionTip = false

Vue.prototype.$store = store

App.mpType = 'app'

const app = new Vue({
	store,
	...App
})
app.$mount()
demo.vue
methods:{
	minfo() {
				let that=this
				that.apiget('/broker/my/info/dealer',{}).then(res => {
					that.dealer = res.dealer
				});
			}
}

本文地址:https://blog.csdn.net/u013252962/article/details/107516049