uniapp网络请求获取数据_uni-app之网络请求

本文详细介绍了在uni-app中如何进行网络请求,包括`uni.request()`的使用,参数配置,以及如何进行网络请求的封装和拦截器的定义。通过封装,实现了请求的参数初始化、请求和响应的拦截处理,以及错误处理。最后展示了如何在Vue项目中调用这些封装的方法。
摘要由CSDN通过智能技术生成

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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值