uni-app 网络请求的封装

uni-app 网络请求的封装

一、index.config.js

const CONFIG = {
    // 开发环境配置
    development: {
        baseUrl: ''
    },
    // 生产环境配置
    production: {
        baseUrl: ''
    }
}

export default CONFIG[process.env.NODE_ENV]

二、request.js

import indexConfig from '@/config/index.config.js'

const baseUrl = indexConfig.baseUrl

const baseRequest = (url, method, data, {}) => {
    uni.showLoading({
        title: '加载中'
    })
    
    let token = uni.getStorageSync('token')		// 用户token
    
    // 设置消息头
    let header = method == 'get' ? {
        'X-Requested-With': 'XMLHttpRequest',
		'Accept': 'application/json',
		'Content-Type': 'application/json; charset=UTF-8'
    } : {
        'X-Requested-With': 'XMLHttpRequest',
		'Content-Type': 'application/json; charset=UTF-8'
    }
    
    // 传参格式
    let dataType = 'json'
    
    // 判断是否有token
    if (token) {
        header['token'] = token
    }
    
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            method: method || 'GET',
            header: header,
            data: data || {},
            success(res) {
                uni.hideLoading()
                // 根据具体返回进行判断
                if (res.data.code == '00000') {
                    resolve(res.data)
                } else {
                    reject(res.data.msg || '系统错误')
                }
            },
            fail(err) {
                uni.hideLoading()
                reject('请求失败')
            }
        })
    })
}

const request = {}

let methodArray = ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect']

methodArray.forEach((method) => {
    request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
})

export default request

三、在main.js中进行挂载

// 引入请求类
import request from '@/network/request.js'

// 在vue的原型上就行挂载
Vue.prototype.$http = request

四、简单使用

// GET请求
this.$http.get('请求地址', '请求参数', '扩展参数').then(res => {
    
}).catch(err => {
    
})

// POST请求
this.$http.post('请求地址', '请求参数', '扩展参数').then(res => {
    
}).catch(err => {
    
})
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值