tp5 uniapp request函数真机post请求失败总结

前言

这两天想折腾一个发帖的软件,但是一直卡在uniapp用request发送请求时后端一直提示的都是GET请求的问题,感觉网上的方法都试遍了,就是没有解决。

场景复现

后端代码:

if (!Request::instance() -> isPost()) {
     exit('提交方式错误');
}

uniapp代码

uni.request({
	url: 'http://www.xxx.cn/xxx/articleAdd',
	method: 'POST',
	success: (res) => {
		console.log(res.data);
	}
});

出现的问题

Request::instance() -> isPost() 一直都是false,然后用method函数打印也一直都是GET。用hbuilderx内置浏览器和浏览器调试都没有问题,但是 一上真机就报错(提交方式错误)。

问题解决过程

网上查的是需要在后端添加下面的代码。原因是因为跨域了

public function __construct()
    {
        var_dump(Request::instance() -> method());
        if (Request::instance() -> isOptions()) {
            header('Access-Control-Allow-Origin:*');
            header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
            header('Access-Control-Allow-Credentials:true');
            header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
            header('Access-Control-Max-Age:1728000');
            header('Content-Type:text/plain charset=UTF-8');
            header('Content-Length: 0', true);
            header('status: 204');
            header('HTTP/1.0 204 No Content');
        } else{
            header('Access-Control-Allow-Origin:*');
            header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
            header('Access-Control-Allow-Credentials:true');
            header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
        }
    }

uniapp中添加下面代码

header: {
	'Content-Type': 'application/x-www-form-urlencoded',
	'X-Requested-With': 'xmlhttprequest'
},

最后我尝试了上面的方法是无效的。

最终解决

最后我发现我的是因为https和http的原因,找了好久才找到。

最后将url: 'http://www.xxx.cn/xxx/articleAdd'中http改为https即可

注意点: 我的服务器是开了强制HTTPS。

原文地址:

tp5 uniapp request函数真机post请求失败总结-小何博客前言 这两天想折腾一个发帖的软件,但是一直卡在uniapp用request发送请求时后端一直提示的都是GET请求的问题,感觉网上的方法都试遍了,就是没有解决。 场景复现 后端代码: if (!Requhttps://ligo100.cn/houduanjishu/php/241.html

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值