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')
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'
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.prototype.$http = request
四、简单使用
this.$http.get('请求地址', '请求参数', '扩展参数').then(res => {
}).catch(err => {
})
this.$http.post('请求地址', '请求参数', '扩展参数').then(res => {
}).catch(err => {
})