uni-app之网络请求
一,介绍
uni.request(OBJECT),发起网络请求,以下主要是一些特殊的参数说明,详细的可查看uni-app官网。
1,method的有效值必须是大写,默认GET方式;
2,success 返回参数说明
参数
类型
说明
data
Object/String/ArrayBuffer
开发者服务器返回的数据
statusCode
Number
开发者服务器返回的 HTTP 状态码
header
Object
开发者服务器返回的 HTTP Response Header
3,传参数据说明
最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String。转换规则如下:
对于 GET 方法,会将数据转换为 query string。例如 { name: 'name', age: 18 } 转换后的结果是 name=name&age=18。
对于 POST 方法且 header['content-type'] 为 application/json 的数据,会进行 JSON 序列化。
对于 POST 方法且 header['content-type'] 为 application/x-www-form-urlencoded 的数据,会将数据转换为 query string。
二,网络请求封装
第一步:参数统一初始化配置
import { configBaseUrl, GET } from "./const"
config: {
baseUrl: configBaseUrl,
header: {
'Content-Type': 'application/json;charset=UTF-8',
},
data: {},
method: GET,
dataType: "json", /* 如设为json,会对返回的数据做一次 JSON.parse */
responseType: "text",
success() { },
fail() { },
complete() { }
},
第二步:拦截器定义
interceptor: {
request: null,
response: null
},
第三步:处理传入的参数
options.baseUrl = options.baseUrl || this.config.baseUrl
options.dataType = options.dataType || this.config.dataType
options.url = options.baseUrl + options.url
options.data = options.data || {}
options.method = options.method.toUpperCase() || this.config.method
// 请求头部类型提供自定义
const contentType = options.contentType;
delete options.contentType;// // 'Content-Type': 'application/x-www-form-urlencoded'
const headers = contentType ? { 'Content-Type': contentType } : this.config.baseUrl; //默认 application/json;charset=UTF-8 json数据传参
options.header = Object.assign({}, options.header, headers);
第四步:发送网络请求
使用Promise方法,方便调用获取返回的参数;并做统一的处理以及日志记录。
return new Promise((resolve, reject) => {
let _config: any = null
options.complete = (response: any) => {
let statusCode = response.statusCode
response.config = _config
if (process.env.NODE_ENV === 'development') {
if (statusCode === 200) {
console.log("【" + _config.requestId + "】 结果:" + JSON.stringify(response.data))
}
}
if (this.interceptor.response) {
// @ts-ignore
let newResponse = this.interceptor.response(response)
if (newResponse) {
response = newResponse
}
}
// 统一的响应日志记录
_reslog(response)
if (statusCode === 200) { //成功
const result = _getResult(response.data);//网络请求成功后数据处理
resolve(result);
} else {
reject(response)
}
}
_config