# 网络请求
luch-request
基于Promise开发的跨平台、项目级别的请求库,它有更小的体积,易用的api,方便简单的自定义能力。
说明
该网络请求luch-request
来源于uni-app插件市场优秀的开源作品luch-request,本文档只对重要的功能进行介绍,如果需要更详细的说明,请参考luch-request官方文档。
# 前言
dnvue-ui已内置优秀的开源作品 luch-request
网络请求,无需引入
# 准备工作
在 .dnvue/common/request.js
中设置全局配置
import Request from '@/uni_modules/dnvue-ui/plug-in/luch-request/index.js'
const getTokenStorage = () => {
let token = ''
try {
token = uni.getStorageSync('token')
} catch (e) {}
return token
}
const http = new Request()
/**
* 修改全局配置示例
const http = new Request({
header: {a:1}, // 举例
baseURL: 'https://www.fastmock.site/mock/26243bdf9062eeae2848fc67603bda2d/luchrequest',
validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置
return statusCode >= 200 && statusCode < 300
}
})
http.config.baseURL = 'https://www.fastmock.site/mock/26243bdf9062eeae2848fc67603bda2d/luchrequest'
**/
http.setConfig((config) => { /* 设置全局配置 */
config.baseURL = 'https://www.fastmock.site/mock/26243bdf9062eeae2848fc67603bda2d/luchrequest'
config.header = {
...config.header,
a: 1, // 演示
b: 2 // 演示
}
config.custom = {
// auth: false, // 是否传token
// loading: false // 是否使用loading
}
return config
})
http.interceptors.request.use((config) => { /* 请求之前拦截器。可以使用async await 做异步操作 */
config.header = {
...config.header,
a: 3 // 演示
}
/**
* custom {Object} - 自定义参数
*/
// if (config.custom.auth) {
// config.header.token = '123456'
// }
// if (config.custom.loading) {
// uni.showLoading()
// }
/*
if (!token) { // 如果token不存在,return Promise.reject(config) 会取消本次请求
return Promise.reject(config)
}
*/
return config
}, (config) => {
return Promise.reject(config)
})
http.interceptors.response.use((response) => { /* 请求之后拦截器。可以使用async await 做异步操作 */
// if (response.config.custom.loading) {
// uni.hideLoading()
// }
if (response.data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
return Promise.reject(response)
}
return response
}, (response) => { // 请求错误做点什么。可以使用async await 做异步操作
// if (response.config.custom.loading) {
// uni.hideLoading()
// }
return Promise.reject(response)
})
export default http;
# 实例方法
this.$store.http.middleware(config)
this.$store.http.request(config)
this.$store.http.get(url[, config])
this.$store.http.upload(url[, config])
this.$store.http.delete(url[, data[, config]])
this.$store.http.head(url[, data[, config]])
this.$store.http.post(url[, data[, config]])
this.$store.http.put(url[, data[, config]])
this.$store.http.connect(url[, data[, config]])
this.$store.http.options(url[, data[, config]])
this.$store.http.trace(url[, data[, config]])
# 使用 GET
请求
this.$store.http.get('/user/login', {params: {userName: 'name', password: '123456'}}).then(res => {
}).catch(err => {
})
// 局部修改配置,局部配置优先级高于全局配置
this.$store.http.get('/user/login', {
params: {userName: 'name', password: '123456'}, /* 会加在url上 */
header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */
dataType: 'json',
// 注:如果局部custom与全局custom有同名属性,则后面的属性会覆盖前面的属性,相当于Object.assign(全局,局部)
custom: {auth: true}, // 可以加一些自定义参数,在拦截器等地方使用。比如这里我加了一个auth,可在拦截器里拿到,如果true就传token
// #ifndef MP-ALIPAY || APP-PLUS
responseType: 'text',
// #endif
// #ifdef MP-ALIPAY || MP-WEIXIN
timeout: 30000, // 仅微信小程序(2.10.0)、支付宝小程序支持
// #endif
// #ifdef APP-PLUS
sslVerify: true, // 验证 ssl 证书 仅5+App安卓端支持(HBuilderX 2.3.3+)
// #endif
// #ifdef APP-PLUS
firstIpv4: false, // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+)
// #endif
// #ifdef H5
withCredentials: false, // 跨域请求时是否携带凭证(cookies)仅H5支持(HBuilderX 2.6.15+)
// #endif
// 返回当前请求的task, options。请勿在此处修改options。非必填
getTask: (task, options) => {
// setTimeout(() => {
// task.abort()
// }, 500)
},
//validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置。演示,非必填选项
// return statusCode >= 200 && statusCode < 300
//}
}).then(res => {
}).catch(err => {
})
# 使用 post
请求
this.$store.http.post('/user/login', {userName: 'name', password: '123456'} ).then(res => {
}).catch(err => {
})
// 局部修改配置,局部配置优先级高于全局配置
this.$store.http.post('/user/login', {userName: 'name', password: '123456'}, {
params: {}, /* 会加在url上 */
header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */
dataType: 'json',
// 注:如果局部custom与全局custom有同名属性,则后面的属性会覆盖前面的属性,相当于Object.assign(全局,局部)
custom: {auth: true}, // 可以加一些自定义参数,在拦截器等地方使用。比如这里我加了一个auth,可在拦截器里拿到,如果true就传token
// #ifndef MP-ALIPAY || APP-PLUS
responseType: 'text',
// #endif
// #ifdef MP-ALIPAY || MP-WEIXIN
timeout: 30000, // 仅微信小程序(2.10.0)、支付宝小程序支持
// #endif
// #ifdef APP-PLUS
sslVerify: true, // 验证 ssl 证书 仅5+App安卓端支持(HBuilderX 2.3.3+)
// #endif
// #ifdef APP-PLUS
firstIpv4: false, // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+)
// #endif
// #ifdef H5
withCredentials: false, // 跨域请求时是否携带凭证(cookies)仅H5支持(HBuilderX 2.6.15+)
// #endif
// 返回当前请求的task, options。请勿在此处修改options。非必填
getTask: (task, options) => {
// setTimeout(() => {
// task.abort()
// }, 500)
},
//validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置。演示,非必填选项
// return statusCode >= 200 && statusCode < 300
//}
}).then(res => {
}).catch(err => {
})
# 使用 upload
请求
this.$store.http.upload('api/upload/img', {
params: {}, /* 会加在url上 */
// #ifdef APP-PLUS || H5
files: [], // 需要上传的文件列表。使用 files 时,filePath 和 name 不生效。App、H5( 2.6.15+)
// #endif
// #ifdef MP-ALIPAY
fileType: 'image/video/audio', // 仅支付宝小程序,且必填。
// #endif
filePath: '', // 要上传文件资源的路径。
// 注:如果局部custom与全局custom有同名属性,则后面的属性会覆盖前面的属性,相当于Object.assign(全局,局部)
custom: {auth: true}, // 可以加一些自定义参数,在拦截器等地方使用。比如这里我加了一个auth,可在拦截器里拿到,如果true就传token
name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */
formData: {}, // HTTP 请求中其他额外的 form data
// 返回当前请求的task, options。请勿在此处修改options。非必填
getTask: (task, options) => {
// task.onProgressUpdate((res) => {
// console.log('上传进度' + res.progress);
// console.log('已经上传的数据长度' + res.totalBytesSent);
// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
//
// // 测试条件,取消上传任务。
// if (res.progress > 50) {
// uploadTask.abort();
// }
// });
},
//validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置。演示,非必填选项
// return statusCode >= 200 && statusCode < 300
//}
}).then(res => {
// 返回的res.data 已经进行JSON.parse
}).catch(err => {
})
# luch-request API
# request
this.$store.http.request({
method: 'POST', // 请求方法必须大写
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
// #ifdef MP-ALIPAY || MP-WEIXIN
timeout: 30000, // 仅微信小程序(2.10.0)、支付宝小程序支持
// #endif
params: { // 会拼接到url上
token: '1111'
},
// #ifdef APP-PLUS
firstIpv4: false, // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+)
// #endif
// 注:如果局部custom与全局custom有同名属性,则后面的属性会覆盖前面的属性,相当于Object.assign(全局,局部)
custom: {}, // 自定义参数
// 返回当前请求的task, options。请勿在此处修改options。非必填
getTask: (task, options) => {
// setTimeout(() => {
// task.abort()
// }, 500)
},
//validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置。演示,非必填选项
// return statusCode >= 200 && statusCode < 300
//}
})
# upload
// 具体参数说明:[uni.uploadFile](https://uniapp.dcloud.io/api/request/network-file)
this.$store.http.upload('api/upload/img', {
params: {}, /* 会加在url上 */
// #ifdef APP-PLUS || H5
files: [], // 需要上传的文件列表。使用 files 时,filePath 和 name 不生效。App、H5( 2.6.15+)
// #endif
// #ifdef MP-ALIPAY
fileType: 'image/video/audio', // 仅支付宝小程序,且必填。
// #endif
filePath: '', // 要上传文件资源的路径。
name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */
custom: {}, // 自定义参数
formData: {}, // HTTP 请求中其他额外的 form data
// 返回当前请求的task, options。请勿在此处修改options。非必填
getTask: (task, options) => {
// setTimeout(() => {
// task.abort()
// }, 500)
},
//validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置。演示,非必填选项
// return statusCode >= 200 && statusCode < 300
//}
}).then(res => {
// 返回的res.data 已经进行JSON.parse
}).catch(err => {
})
# download
// 具体参数说明:[uni.downloadFile](https://uniapp.dcloud.io/api/request/network-file?id=downloadfile)
this.$store.http.download('api/download', {
params: {}, /* 会加在url上 */
header: {}, /* 会与全局header合并,如有同名属性,局部覆盖全局 */
custom: {}, // 自定义参数
// 返回当前请求的task, options。非必填
getTask: (task, options) => {
// setTimeout(() => {
// task.abort()
// }, 500)
},
//validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置。演示,非必填选项
// return statusCode >= 200 && statusCode < 300
//}
}).then(res => {
}).catch(err => {
})
# middleware
所有请求方式的超集。包含UPLOAD、DOWNLOAD方法。对应method使用对应参数。
this.$store.http.middleware({
method: 'POST', // 请求方法必须大写 [GET|POST|PUT|DELETE|CONNECT|HEAD|OPTIONS|TRACE|UPLOAD|DOWNLOAD]
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
// #ifdef MP-ALIPAY || MP-WEIXIN
timeout: 30000, // 仅微信小程序(2.10.0)、支付宝小程序支持
// #endif
params: { // 会拼接到url上
token: '1111'
},
// #ifdef APP-PLUS
firstIpv4: false, // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+)
// #endif
// 注:如果局部custom与全局custom有同名属性,则后面的属性会覆盖前面的属性,相当于Object.assign(全局,局部)
custom: {}, // 自定义参数
// 返回当前请求的task, options。请勿在此处修改options。非必填
getTask: (task, options) => {
// setTimeout(() => {
// task.abort()
// }, 500)
},
//validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置。演示,非必填选项
// return statusCode >= 200 && statusCode < 300
//}
})
# 全局请求配置
# 可配置项
{
baseURL: '',
header: {},
method: 'GET',
dataType: 'json',
// #ifndef MP-ALIPAY || APP-PLUS
responseType: 'text',
// #endif
// 注:如果局部custom与全局custom有同名属性,则后面的属性会覆盖前面的属性,相当于Object.assign(全局,局部)
custom: {}, // 全局自定义参数默认值
// #ifdef MP-ALIPAY || MP-WEIXIN
timeout: 30000,
// #endif
// #ifdef APP-PLUS
sslVerify: true,
// #endif
// #ifdef H5
// 跨域请求时是否携带凭证(cookies)仅H5支持(HBuilderX 2.6.15+)
withCredentials: false,
// #endif
// #ifdef APP-PLUS
firstIpv4: false, // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+)
// #endif
// 局部优先级高于全局,返回当前请求的task,options。请勿在此处修改options。非必填
// getTask: (task, options) => {
// 相当于设置了请求超时时间500ms
// setTimeout(() => {
// task.abort()
// }, 500)
// },
// 全局自定义验证器。参数为statusCode 且必存在,不用判断空情况。
validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置
return statusCode >= 200 && statusCode < 300
}
}
# 全局配置修改setConfig
/**
* @description 修改全局默认配置
* @param {Function}
*/
http.setConfig((config) => { /* config 为默认全局配置*/
config.baseURL = 'http://www.bbb.cn'; /* 根域名 */
config.header = {
a: 1, // 演示用
b: 2 // 演示用
}
return config
})
// 方式二
const test = new Request({
header: {a:1}, // 演示
// ... 其他全局配置项
})
// 方式三
test.config.header = {c:1}
test.config.baseURL = 'https://quanzhan.co'
# 拦截器
# 在请求之前拦截
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
config.header = {
...config.header,
a: 1 // 演示拦截器header加参
}
// 演示custom 用处
// if (config.custom.auth) {
// config.header.token = 'token'
// }
// if (config.custom.loading) {
// uni.showLoading()
// }
/**
/* 演示
if (!token) { // 如果token不存在,return Promise.reject(config) 会取消本次请求
return Promise.reject(config)
}
**/
return config
}, config => { // 可使用async await 做异步操作
return Promise.reject(config)
})
# 在请求之后拦截
http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
// if (response.data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
// return Promise.reject(response) // return Promise.reject 可使promise状态进入catch
// if (response.config.custom.verification) { // 演示自定义参数的作用
// return response.data
// }
console.log(response)
return response
}, (response) => { /* 对响应错误做点什么 (statusCode !== 200)*/
console.log(response)
return Promise.reject(response)
})
← 表单验证/数据验证 UUID 唯一标识符 →