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

uni-app封装请求方法

程序员文章站 2022-07-08 10:12:05
新建http.js,写入请求的封装方法,在页面调用;//http.jsconst baseUrl = 'http://www.baidu.com'; //请求地址//get请求封装function gets(url, data) {var promise = new Promise((resolve, reject) => {var postData = data;uni.request({url: baseUrl + url,data: postData,...
新建http.js,写入请求的封装方法,在页面调用;

//http.js
const baseUrl = 'http://www.baidu.com';  //请求地址
//get请求封装
function gets(url, data) {
	var promise = new Promise((resolve, reject) => {
		var postData = data;
		uni.request({
			url: baseUrl + url,
			data: postData,
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				"accept": "*/*",
			},
			success: function(res) {
				if (res.data.code === 200 && res.data.code == 0) {
					resolve(res.data);
				} else {
					resolve(res.data)
				}
			},
			error: function(e) {
				reject('网络出错');
			}
		})
	});
	return promise;
}
//post请求封装
function post(url, data) {
	var promise = new Promise((resolve, reject) => {
		var postData = data;
		uni.request({
			url: baseUrl + url,
			data: postData,
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				"accept": "*/*",
			},
			success: function(res) {
				if (res.data.code === 200 && res.data.code == 0) {
					resolve(res.data);
				} else {
					resolve(res.data)
				}
			},
			error: function(e) {
				reject('网络出错');
			}
		})
	});
	return promise;
}
export default {
	baseUrl,
	gets,
	post,
}
示例:import $ from '../../../http/http.js'
getData(){
	let t = this;
	let url = "/api/assets/list";
	let params = {};
	$.post(url,params).then(r =>{
		console.log(r)
	}).catch(err =>{
		console.log(err)
	})
},

本文地址:https://blog.csdn.net/WangYi0118/article/details/108725123

相关标签: javasript