beego 框架获取不到小程序 POST 数据
问题描述
默认情况下小程序请求 wx.request POST 时 header['content-type'] = 'application/json' ,如果在 beego controller 中通过 this.getString('name') 是获取不到值的。
解决方法一
设置微信小程序 wx.request 请求时的 header content-type 为 'application/x-www-form-urlencoded'
wx.request({
url: 'https://demo.nideshop.com/api/auth/weapp/login',
method: "POST",
header: {
"content-type": "application/x-www-form-urlencoded"
},
data: {
code: this.data.code,
raw_data: e.detail.rawData,
encrypted_data: e.detail.encryptedData,
signature: e.detail.signature,
iv: e.detail.iv,
},
success (res) {
console.log(res)
}
})
解决方法二
beego 获取 Request Body 里的内容
在配置文件里设置 copyrequestbody = true
解析 json 到结构体中
type WeappLoginParam struct {
Code string `json:"code"`
RawData string `json:"raw_data"`
EncryptedData string `json:"encrypted_data"`
Signature string `json:"signature"`
IV string `json:"iv"`
}
var param WeappLoginParam
if err := json.Unmarshal(this.Ctx.Input.RequestBody, ¶m); err != nil {
beego.Error("json.Unmarshal 错误 err = ", err.Error())
}