巅云php学苑
近期车展
最新发布
快速导航

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

前端开发 / 前端框架 / 2022-04-03 22:14
visits visits 966 collect - report - QRcode

Basicinformation

content

遇到的坑:

例如在写微信小程序接口时,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 appcarcontroller;
use thinkController;
use thinkDb;
use thinkRequest;
 
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请求时后端无法获取数据内容请搜索IT博客社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT博客社区!

notmore

Users comments(0)

rate100%
  • notmore
+ more
  • contacts:
  • area:
  • tel: total(2007)twigs area:unknown

联系我们

合作或咨询可通过如下方式:

QQ/微信:123456

网址:www.xxxx.cn

微信公众号:车展门票

关于本站

「车展网www.xxxxxxx.cn」是一个集全国各地品牌经销车商的平台,让您在所在城市,第一时间收到车展的最新消息,让您的试驾、选车、购车、贷车一步到位,更多优惠直达客户,无需东奔西走,带上中意的车回家,让您省钱,更省心。

Copyright 车展网 www.xxxx.cn Reserved渝ICP备xxxxxxxx号

关注我们