小程序数据请求1.0

it2026-03-26  7

request

属性请求示例1请求示例2(封装)解析1.了解解构规则2. 可改为如下3. 所以

属性

属性名类型默认值介绍urlstring接口地址datastring/object/ArrayBuffer参数headerObject设置请求的 header,header 中不能设置 Referer。content-type 默认为 application/jsontimeoutnumber超时时间,单位为毫秒methodstringGET请求方法dataTypestringjson返回的数据格式responseTypestringtext响应的数据类型successfunction接口调用成功的回调函数failfunction接口调用失败的回调函数completefunction接口调用结束的回调函数(调用成功、失败都会执行)

请求示例1

wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 data: { x: '', y: '' }, header: { 'content-type': 'application/json' // 默认值,可不填 }, success (res) { console.log(res.data) } })

其他未出现是属性都是 非必填 的值

请求示例2(封装)

// 统一的请求接口 const baseUrl = 'https://lpc.0791jr.com/api'; //简化请求接口 const getUrl = (url) => { if (url.indexOf('://') == -1) { url = baseUrl + url; } return url } const http = ({ url = '', param = {}, ...other } = {}) => { return new Promise((resolve, reject) => { wx.request({ url: getUrl(url), data: param, header: { "content-type": "application/x-www-form-urlencoded;charset=UTF-8" }, ...other, complete: (res) => { resolve(res.data) } else { //请求失败 reject(res.data) } } }) }) } // get方法 const _get = (url, param = {}) => { return http({ url, param }) } const _post = (url, param = {}) => { return http({ url, param, method: 'POST' //其实可以不用大写 }) } const _put = (url, param = {}) => { return http({ url, param, method: 'PUT' }) } const _delete = (url, param = {}) => { return http({ url, param, method: 'DELETE' }) } module.exports = { baseUrl, get: _get, post: _post, put: _put, delete: _delete }

解析

const http = ({ url = '', param = {}, ...other } = {}) => {}

这段代码一开始可能会看不太懂,下面举个例子

1.了解解构规则

解构赋值的规则是,若等号右边的值不是对象或者数组,就会先将其转化成对象。由于undefined和null无法转化成对象,所以对其进行解构赋值时会报错。

function text(a,b,{c,d}){ // ... } text(1,2,{}); text(1,2)//报错:Uncaught TypeError: Cannot destructure property `c` of 'undefined' or 'null' // 等同于 function text2(a, b, options) { let { c,d } = options; } text2(1,2); //options没传值导致异常报错:Uncaught TypeError: Cannot destructure property `c` of 'undefined' or 'null'

2. 可改为如下

function text(a,b,{c,d}={}){ // ... } function text2(a, b, { c,d } = {}) { // ... } let obj = {1,2} text(1,2) //未报错 text(1,2,obj) //原理解析: 先判断text函数第三个参数有没有传值,未传值则 默认赋值{c,d} = {};若传进来了obj,则{c,d} = obj

也就是说 text(a, b, {c,d}={}){//…} 中的{c,d}={}中的 等号是默认赋值的等号,不是解构赋值的等号

3. 所以

const http = ({ url = '', param = {}, ...other } = {}) => {}

是先看有没有传值 1.若未传值 那么进行默认赋值,在解构

http() /* ================ */ { url = '', param = {}, ...other } = {} 若传值, 对传的值解构 let obj = { url:1, param: 2 } http(obj); /* ================ */ { url = '', param = {}, ...other } = obj
最新回复(0)