乘风原创程序

  • uni-app封装请求方法
  • 2020/9/22 12:01:00
  • 新建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