核心提示:微信小程序开发中网络请求必不可少.GET.POST请求是最常用的.GET请求POST请求的时候有好几个坑.我已经为大家填好了.按照文档,肯定是这么写.那就入坑了.1.Content-Type: app...
微信小程序开发中网络请求必不可少.GET.POST请求是最常用的.GET请求
POST请求的时候有好几个坑.我已经为大家填好了.
按照文档,肯定是这么写.那就入坑了.
1.'Content-Type': 'application/json'用在get请求中没问题.
POST请求就不好使了.需要改成:"Content-Type": "application/x-www-form-urlencoded"
2016.11.10更新:有同学在将content-type 修改为小写后,post请求成功.2.加上method: "POST"
3.data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }写成json格式这样也是请求不到数据的.需要转格式.
下面直接贴代码:
3.1
//获取应用实例 var app = getApp() Page( { data: { toastHidden: true, city_name: '', }, onLoad: function() { that = this; wx.request( { url: "https://op.juhe.cn/onebox/weather/query", header: { "Content-Type": "application/x-www-form-urlencoded" }, method: "POST", //data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }, data: Util.json2Form( { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }), complete: function( res ) { that.setData( { toastHidden: false, toastText: res.data.reason, city_name: res.data.result.data.realtime.city_name, date: res.data.result.data.realtime.date, info: res.data.result.data.realtime.weather.info, }); if( res == null || res.data == null ) { console.error( '网络请求失败' ); return; } } }) }, onToastChanged: function() { that.setData( { toastHidden: true }); } }) var that; var Util = require( '../../utils/util.js' );3.2wxml:
{{toastText}} {{city_name}} {{date}} {{info}}
3.3 utils中定义
function json2Form(json) { var str = []; for(var p in json){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p])); } return str.join("&"); } module.exports = { json2Form:json2Form, }这样就可以请求成功了!