微信小程序使用content-type等於x-www-form-urlencoded方式使用request請求數據
阿新 • • 發佈:2018-11-11
user ESS sharp lis 小程序開發 功能 request請求 你是 for
因為服務器只能接收x-www-form-urlencoded方式接收前端收到的數據 所以微信小程序開發的時候,必須鼓搗這個問題。
微信默認使用content-type是 application/json
用wx.request方法改掉header為x-www-form-urlencoded比較簡單
wx.request({ ‘content-type‘: ‘application/x-www-form-urlencoded‘ })
這麽幹就可以了。
但問題是,微信小程序,似乎不會把我們的數據自動轉換成為該格式數據。
解決方案是使用下面這種方法
function JSON_to_URLEncoded(element,key,list){ var list = list || []; if(typeof(element)==‘object‘){ for (var idx in element) JSON_to_URLEncoded(element[idx],key?key+‘[‘+idx+‘]‘:idx,list); } else { list.push(key+‘=‘+encodeURIComponent(element)); } return list.join(‘&‘); }
測試
var data = { ‘users‘ : [ { "id": 100, "name": "Stefano" }, { "id": 200, "name": "Lucia" }, { "id": 300, "name": "Franco" }, ], ‘time‘ : +new Date }; console.log( JSON_to_URLEncoded(data) ); /* Output: users[0][id]=100&users[0][name]=Stefano&users[1][id]=200&users[1][name]=Lucia&users[2][id]=300&users[2][name]=Franco&time=1405014230183*/
如果你是使用ES2015,試試一行代碼實現這個方法功能。 但你是復雜的數據,還是不要用下面這個方法了。
const toUrlEncoded = obj => Object.keys(obj).map(k => encodeURIComponent(k) + ‘=‘ + encodeURIComponent(obj[k])).join(‘&‘); toUrlEncoded({hello: ‘world‘, message: "JavaScript is cool"}); // => "hello=world&message=JavaScript%20is%20cool"
微信小程序使用content-type等於x-www-form-urlencoded方式使用request請求數據