首頁  >  文章  >  微信小程式  >  微信小程式網路請求的封裝

微信小程式網路請求的封裝

巴扎黑
巴扎黑原創
2017-09-19 09:21:101959瀏覽

在這裡先宣告一個小程式文件的bug,導致大夥們在請求的時候,伺服器收到不到參數的問題
範例程式碼:

wx.request({
 url: 'test.php', //仅为示例,并非真实的接口地址
 data: {
 x: '' ,
 y: ''
 },
 header: {
 'Content-Type': 'application/json'
 },
 success: function(res) {
 console.log(res.data)
 }
})


其中header 中的Content-Type,應該用小寫content-type才能讓伺服器收到參數。讓我折騰的好久,改了伺服器還是不行,原來是這個問題。參數在request payload中,伺服器不能收到,使用如下轉換之後

function json2Form(json) { 
 var str = []; 
 for(var p in json){ 
 str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p])); 
 } 
 return str.join("&"); 
}



圖片:1.png

微信小程式網路請求的封裝

最終還是認為是content-type的問題。最後改小寫就ok,覺得微信這麼屌的團隊,犯了一個很低級 的錯誤,把我開發者折騰的爬了。不說,上代碼吧。
1 、Http請求的類別

import util from 'util.js';
/**
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _get( url, success, fail ) {
  
 console.log( "------start---_get----" );
 wx.request( {
 url: url,
 header: {
  // 'Content-Type': 'application/json'
 },
 success: function( res ) {
  success( res );
 },
 fail: function( res ) {
  fail( res );
 }
 });
 console.log( "----end-----_get----" );
}
/**
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _post_from(url,data, success, fail ) {
 console.log( "----_post--start-------" );
 wx.request( {
 url: url,
 header: {
 'content-type': 'application/x-www-form-urlencoded',
 },
 method:'POST',
 data:{data: data},
 success: function( res ) {
  success( res );
 },
 fail: function( res ) {
  fail( res );
 }
 });
 console.log( "----end-----_get----" );
}
  
 /**
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _post_json(url,data, success, fail ) {
 console.log( "----_post--start-------" );
 wx.request( {
 url: url,
 header: {
  'content-type': 'application/json',
 },
 method:'POST',
 data:data,
 success: function( res ) {
  success( res );
 },
 fail: function( res ) {
  fail( res );
 }
 });
 console.log( "----end----_post-----" );
}
module.exports = {
 _get: _get,
 _post:_post,
 _post_json:_post_json
}


2、測試案例
## 2.1 get請求

//GET方式
let map = new Map();
map.set( 'receiveId', '0010000022464' );
let d = json_util.mapToJson( util.tokenAndKo( map ) );
console.log( d );
var url1 = api.getBaseUrl() + 'SearchTaskByReceiveId?data='+d;
network_util._get( url1,d,
function( res ) {
console.log( res );
that.setData({
 taskEntrys:res.data.taskEntrys
});
}, function( res ) {
console.log( res );
});


2.2 POST請求

//Post方式
 let map = new Map();
 map.set( 'receiveId', '0010000022464' );
 let d = json_util.mapToJson( util.tokenAndKo( map ) );
 console.log( d );
 var url1 = api.getBaseUrl() + 'SearchTaskByReceiveId';
 network_util._post( url1,d,
 function( res ) {
 console.log( res );
 that.setData({
  taskEntrys:res.data.taskEntrys
 });
 }, function( res ) {
 console.log( res );
 });



圖片:2.png微信小程式網路請求的封裝


#效果


微信小程式網路請求的封裝圖:3.png

#######

以上是微信小程式網路請求的封裝的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn