這篇文章主要介紹了微信小程序wx.request使用POST請求時后端無法獲取數據解決辦法,解決辦法其實也很簡單,有需要的同學可以嘗試下
遇到的坑:
例如在寫微信小程序接口時,method請求方式有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);
}
}





