微信小程序wx.request使用POST请求时后端无法获取数据解决办法

 2959

这篇文章主要介绍了微信小程序wx.request使用POST请求时后端无法获取数据解决办法,解决办法其实也很简单,有需要的同学可以尝试下

遇到的坑:

例如在写微信小程序接口时,method请求方式有POST和GET两种,为了数据安全,我们会偏向于使用POST请求方式访问服务器端;

当我们使用POST方式请求时,后端无法获取到传送的参数,但使用GET方式却是可以的。

解决办法:

设置请求的 header头:

header: { "Content-Type": "application/x-www-form-urlencoded" },


微信小程序wx.request使用POST请求时后端无法获取数据解决办法


特别注意: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);
    }
}



本文网址:https://www.zztuku.com/detail-8720.html
站长图库 - 微信小程序wx.request使用POST请求时后端无法获取数据解决办法
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐