今天在学习开发微信小程序时发现遇到一个奇怪的问题,用wx.request()发送https请求到后端,但是后端无法获取到发送过去的post数据。
刚开始学习开发微信小程序我是跟着网上的一些视频来做的,后来发现他讲的有的东西已结被淘汰掉了,用不了,然后我就自己看微信官方的文档来慢慢跟着写代码。
官方的wx.request()实例是下面这个:
wx.request({
url: 'example.php', //仅为示例,并非真实的接口地址
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data)
}
})
我直接复制使用,把接口地址改掉之后发现发送的data后端无法获取到,然后也是在百度找了一下发现了问题的所在,因为默认的header是’application/json’我们需要把它改为’application/x-www-form-urlencoded’然后就OK了。
成功的代码如下:
wx.request({
url: 'https://bcdog.cn',
method:'POST',
data:{name:"1"},
header: {
'content-type': 'application/x-www-form-urlencoded' // 默认值
},
success:(res) => {
console.log(res.data)
this.setData({
userList:res.data
})
}
})
关于data可以看一下下面这个,我从微信官方copy的
data 参数说明
最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:
- 对于
GET
方法的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...
) - 对于
POST
方法且header['content-type']
为application/json
的数据,会对数据进行 JSON 序列化 - 对于
POST
方法且header['content-type']
为application/x-www-form-urlencoded
的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)
© 版权声明
如果没有特殊说明,文章版权归编程狗所有,转载请注明出处。
THE END
暂无评论内容