遇到的坑:
例如在寫微信小程序接口時,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);
}
}
到此這篇關于微信小程序wx.request使用POST請求時后端無法獲取數據解決辦法的文章就介紹到這了,更多相關微信小程序使用POST請求時后端無法獲取數據內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 微信小程序中網絡請求緩存的解決方法
- Springboot單體架構http請求轉換https請求來支持微信小程序調用接口
- 微信小程序中如何使用flyio封裝網絡請求
- 微信小程序封裝的HTTP請求示例【附升級版】
- 詳解微信小程序網絡請求接口封裝實例
- 微信小程序使用wx.request請求服務器json數據并渲染到頁面操作示例