uni-app数据请求封装

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

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)
				}) 

 

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页