介绍
这篇文章给大家分享的是有关微信小程序网络请求封装的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
在这里首先声明一个小程序文档的错误,导致大伙们在请求的时候,服务器收到不到参数的问题
示例代码:
wx.request ({ ,url: & # 39; test.php& # 39;,,//仅为示例,并非真实的接口地址 ,数据:{ ,x: & # 39; & # 39;,, y:大敌;& # 39;& # 39; }, ,头:{ ,& # 39;内容类型# 39;:,& # 39;application/json # 39; }, ,成功:函数(res), { ,console.log (res.data) ,} })
其中头中的内容类型,应该用小写内容类型才能让服务器收到参数。让我折腾的好久,改了服务器仍然不行,原来是这个问题。参数在请求负载中,服务器不能收的到,使用如下转换之后
function json2Form (json), {, ,var str =, [];, ,(var p 拷贝json) {, ,str.push (encodeURIComponent (p), +,“=? +, encodeURIComponent (json [p])),, }大敌; ,return str.join(”和“),, }
最终还是认为是内容类型的问题。最后改小写就好,觉得微信这么牛逼的团队,犯了一个很低级的错误,把我开发者折腾的爬了。不说,上代码吧。
<强> 1,Http请求的类强>
import util 得到& # 39;util.js& # 39;;/* * ,* url 请求地址 ,* success 成功的回调 ,* fail 失败的回调 ,*/function get (url,大敌;成功,fail ), { ,console.log(,“- - - - - -开始- get - - - - -“,); ,wx.request ({ ,url: url, ,头:{//才能,& # 39;内容类型# 39;:,& # 39;application/json # 39; }, ,成功:函数(),res , { 成功才能(,res ); }, ,失败:函数(),res , { 失败才能(,res ); ,} ,}); ,console.log(结束,“- - - - - - - - - - get - - - - -“,); }/* * ,* url 请求地址 ,* success 成功的回调 ,* fail 失败的回调 ,*/function _post_from (url、数据,成功,fail ), { ,console.log (,“————_post——开始——产生绯闻;,); ,wx.request ({ ,url: url, ,头:{ & # 39;才能- type # 39;:, & # 39;应用程序/x-www-form-urlencoded& # 39; }, ,方法:& # 39;文章# 39; ,数据:}{数据:数据, ,成功:函数(),res , { 成功才能(,res ); }, ,失败:函数(),res , { 失败才能(,res ); ,} ,}); ,console.log(结束,“- - - - - - - - - - get - - - - -“,); }/* * ,* url 请求地址 ,* success 成功的回调 ,* fail 失败的回调 ,*/function _post_json (url、数据,成功,fail ), { ,console.log (,“————_post——开始——产生绯闻;,); ,wx.request ({ ,url: url, ,头:{ & # 39;才能- type # 39;:, & # 39;应用程序/json # 39; }, ,方法:& # 39;文章# 39; ,数据:数据, ,成功:函数(),res , { 成功才能(,res ); }, ,失败:函数(),res , { 失败才能(,res ); ,} ,}); ,console.log(结束,“- - - - - - - - - - _post——产生绯闻,,); } module.exports =, { ,get: get, ,_post: _post, _post_json: _post_json }
<强> 2,测试用例强>
<强> 2.1得到请求强>
,//得到方式 ,let map =, new 地图(); ,map.set (, & # 39; receiveId& # 39;,, & # 39; 0010000022464 & # 39;,); ,let d =, json_util.mapToJson (, util.tokenAndKo (, map ),); ,console.log (, d ); ,var url1 =, api.getBaseUrl (), +, & # 39; SearchTaskByReceiveId ?数据=https://www.yisu.com/zixun/' + d; network_util。get (url1 d 函数(res) { 控制台。日志(res); that.setData ({ taskEntrys: res.data.taskEntrys }); },函数(res) { 控制台。日志(res); });
<强> 2.2后请求强>
//发布方式 ,let map =, new 地图(); ,map.set (, & # 39; receiveId& # 39;,, & # 39; 0010000022464 & # 39;,); ,let d =, json_util.mapToJson (, util.tokenAndKo (, map ),); ,console.log (, d ); ,var url1 =, api.getBaseUrl (), +, & # 39; SearchTaskByReceiveId& # 39;; ,network_util._post (url1 d ,函数(,res ), { ,console.log (, res ); ,that.setData ({ taskEntrys: res.data.taskEntrys才能 ,}); ,},函数(),res , { ,console.log (, res ); null微信小程序网络请求封装的示例分析