微信小程序POST请求参数丢失问题
开发过程中常遇到的一个典型问题:
在构建微信小程序接口时,HTTP请求支持POST与GET两种方式。出于对数据传输安全的考量,开发者往往倾向于采用POST方式来向服务器提交数据;
然而在实际测试中发现,当采用POST方式进行请求时,服务端常常无法接收到前端传递的参数,但切换为GET方式后则能正常获取;
针对上述问题的解决方案如下:
需要在请求配置中明确设置Header头部信息:
header: { "Content-Type": "application/x-www-form-urlencoded" },

需要特别注意的是,POST请求必须显式声明method: 'POST',因为wx.request组件默认的请求方法即为GET;
具体实现示例如下:
以下是微信小程序端index.js中的代码片段:
wx.request({
url: 'https://后端网址/user/updatePhone.html',
method: 'POST',
data: { phone: _phone, openid: _openid},
header: { "Content-Type": "application/x-www-form-urlencoded" },
success: res => {
console.log(res.data);
}
});
ThinkPHP后端控制器处理逻辑:
<?php
namespace app\car\controller;
use think\Controller;
use think\Db;
use think\Request;
class User extends Base
{
public function _initialize(){
parent::_initialize();
}
public function updatePhone(){
if(!isset($_POST['phone'])||!isset($_POST['openid'])){
header("Content-type: text/html; charset=utf-8");
echo '参数错误'.$_POST['phone'];
exit;
}
$openid= trim($_POST['openid']);
try{
$updata['tel'] = trim($_POST['phone']);
Db::name('user')->where('wxopenid',$openid)->update($updata);
$code=1;
$msg="修改成功";
} catch (\Exception $e) {
$code=0;
$msg="修改失败";
}
return $this->outputMsg($code,$msg);
}
}
以上就是关于微信小程序在使用wx.request进行POST请求时后端无法获取数据的解决方案介绍,更多关于微信小程序POST请求传参的问题可查阅本站往期文章或浏览下方推荐内容,感谢大家的支持!