uni-app数据请求封装

1. utils文件夹 -> 新建 request.js

uni-app数据请求封装_第1张图片

request.js :

const baseUrl = 'http://******'  //请求接口地址
const httpRequest = (url, method, data) => {
	let meth = method.toUpperCase();//小写改为大写
	if (!data) {
		data = {}
	}
	
	if(getApp().globalData.token){
		data['token'] = getApp().globalData.token; //token
	}
	
    let httpDefaultOpts = {
        url: baseUrl + url,
        data: data,
        method: meth,
		header:{
			'X-Requested-With': 'XMLHttpRequest',
			'content-type': meth == 'POST' ? 'application/x-www-form-urlencoded' : 'application/json',
		},
        dataType: 'json',
    }
    return new Promise(function(resolve, reject) {
        uni.request(httpDefaultOpts).then(
            (res) => {
				if(res[1].data.status == 0){//成功返回
					resolve(res[1])
				}else{//错误信息
					uni.showToast({
						title:res[1].data.message,
						icon:'none'
					})
                    //resolve(res[1]) //错误信息返不返回 看个人情况
				}
            }
        ).catch(
            (response) => {
                reject(response)
            }
        )
    })
};

export default {
	baseUrl,
	httpRequest				
}

2. main.js  全局引入

//数据请求封装
import http from './utils/request.js'
Vue.prototype.http = http;

3.组件内使用

//有参数
this.http.httpRequest('/v1/goods/category/labels','post',{
					cid:id
				}).then(res => {
					console.log(res)
				}) 

//无参数
this.http.httpRequest('/v1/goods/category/labels','post').then(res => {
					console.log(res)
				}) 

 

你可能感兴趣的:(uni-app)