According to the document, it must be written like this. Then you are in trouble.
1. 'Content-Type': 'application/json' is used in There is no problem with the get request.
The POST request does not work. It needs to be changed to: "Content-Type": "application/x-www-form-urlencoded"
2. Add method: "POST"
3.data: { cityname: "Shanghai", key: "1430ec127e097e1113259c5e1be1ba70" } Even if it is written in json format, the data cannot be requested. The format needs to be converted.
Post the code directly below:
3.1
<span style="font-size:24px;">//index.js //获取应用实例 var app = getApp() Page( { data: { toastHidden: true, city_name: '', }, onLoad: function() { that = this; wx.request( { url: "http://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' );</span>
3.2
<span style="font-size:24px;"><!--index.wxml--> <view class="container"> <toast hidden="{{toastHidden}}" bindchange="onToastChanged"> {{toastText}} </toast> <view>{{city_name}}</view> <view>{{date}}</view> <view>{{info}}</view> </view></span>
3.3
<span style="font-size:24px;">//util.js function json2Form(json) { var str = []; for(var p in json){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p])); } return str.join("&"); } module.exports = { json2Form:json2Form, }</span>
Comment section:
I tried a few more interfaces, and some of them can submit data. It should be a bug. I can only wait for the official version.
I just used other post requests and it didn’t work either. But This does get the data. You can try it. The interface address is: http://op.juhe.cn/onebox/weather/query. There are two parameters, cityname, key.cityname. Just write the city name. I applied for the key. =1430ec127e097e1113259c5e1be1ba70 I will study it tomorrow and see why the others are not working.
For more small programs: post request related articles, please pay attention to the PHP Chinese website!