微信小程序服务端(spring框架)接收参数错误 post接收不到

微信小程序开发中需要注意:小程序只能用标准的https请求,get请求中没问题,但POST请求就不好使了。

原因:小程序请求头'Content-Type': 'application/json'  不同于平常的"application/x-www-form-urlencoded"
解决办法:

1.get请求无所谓,post请求需要封装成bean,用@Requestbody 接收

141527_EqX8_866535.png

另:更改@Requestmapping的consumer

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {    
    // implementation omitted
}

据说也可以,@Requestmapping详解看这里https://my.oschina.net/luanwu/blog/1579775

2.将默认的'Content-Type': 'application/json'  需要改成: "Content-Type": "application/x-www-form-urlencoded"

data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }写成json格式这样也是请求不到数据的.需要转格式.

用别人的代码

<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>  
<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>  
<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>  

 

转载于:https://my.oschina.net/luanwu/blog/1579347

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值