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。

版权声明:
作者:小何
链接:https://ligo100.cn/houduanjishu/php/241.html
来源:小何博客
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>
文章目录
关闭
目 录