封装uni-app的网络请求
方式一:
使用原生uni.request
请求
const BASE_URL = 'http://xxx'
export const request = (options) => {
//加载loading
uni.showLoading({
title:'加载中'
})
let header = {
"Content-Type": "application/json",
"Authorization": uni.getStorageSync('token')
}
console.info(options)
return new Promise((resolve, reject) => {
uni.request({
// 开发者服务器接口地址(请求服务器地址 + 具体接口名)
url: BASE_URL + options.url,
// 请求方式(若不传,则默认为 GET )
method: options.method || 'GET',
// 请求参数(若不传,则默认为 {} )
data: options.data || {
},
// 请求头(若不传,则默认为 header )
header: options.header || header,
// 请求成功
success: (res) => {
// 此判断可根据自己需要更改
if (res.statusCode != 200) {
let msg = error.data.message || error.data
if(msg==null || msg==undefined) msg = '服务器异常'
uni.showToast({
title: msg,
icon: 'none'
})
if(res.statusCode == 401){
setTimeout(() => {
// 跳转到登录页
uni.navigateTo({
url: "/pages/login/login"
})
}, 1000)
return
}
}
resolve(res.data)
},
// 请求失败
fail: (err) => {
uni.showToast({
title: '请求接口失败!',
icon: 'none'
})
reject(err)
},
//请求结束之后,执行的回调函数(成功或失败都会执行)
complete() {
//隐藏loading
uni.hideLoading()
}
})
})
}
export default {
request
}
方式二(推荐使用
):
使用luch-request
进行封装(小程序不支持axios
),把luch
的相关文件放到项目中,如
新建一个js,内容如下:
import Request from '@/utils/luch/index.js'
const BASE_URL = 'http://xxx'
const request = new Request();
/* 设置全局配置 */
request.setConfig((config) => {
config.baseURL = BASE_URL
return config
})
/* 请求以前拦截器 */
request.interceptors.request.use((config) => {
config.header["Content-Type"] = "application/json"
config.header = {
...config.header
}
// 权限认证
config.header.Authorization = uni.getStorageSync("token")
return config
})
request.interceptors.response.use(async (res) => {
/* 请求以后拦截器 */
if (res.statusCode != 200) {
return Promise.reject(res)
}
return res.data
}, (error) => {
// 请求错误
console.log(error)
if (error.statusCode == 401) {
// 登录态失效则清除token:没有携带token、token没法再刷新
let msg = error.data.message || error.data
if(msg==null || msg==undefined) msg = '当前登录状态过期,请重新登录'
uni.clearStorageSync()
uni.showToast({
title: msg,
icon: 'none',
success() {
setTimeout(() => {
// 跳转到登录页
uni.navigateTo({
url: "/pages/login/login"
})
}, 1000)
}
})
}else{
let msg = error.data.message || error.data
uni.showToast({
title: msg,
icon: 'none',
duration: 2000
})
}
return Promise.reject(error)
})
export {
request
}
在main.js
中引入
import {
request} from '@/utils/request.js'
Vue.prototype.$request = request
使用
//get方法
this.$request.get(url).then(res=>{
console.info(res)
})
//put方法
this.$request.put(rul, param).then(res => {
console.info(res)
})
//delete方法
this.$request.delete(url, param).then(res => {
console.info(res)
})
//post方法
this.$request.post(url,this.param).then(res=>{
console.info(res)
})
//上传文件
this.$request.upload(url,{
filePath: tempFilePaths[0],
name: 'file',
}).then(res => {
console.log(res)
})
还没有评论,来说两句吧...