发帖最好的软件 tp5 uniapp request函数真机post请求失败总结
前言这两天想折腾一个发帖的软件,但是一直卡在用发送请求时后端一直提示的都是GET请求的问题,感觉网上的方法都试遍了,就是没有解决。
前言
这两天想折腾一个发帖的软件,但是一直卡在用发送请求时后端一直提示的都是GET请求的问题,感觉网上的方法都试遍了,就是没有解决。
场景复现
后端代码:
if (!Request::instance() -> isPost()) {
exit('提交方式错误');
}
代码
uni.request({
url: 'http://www.xxx.cn/xxx/articleAdd',
method: 'POST',
success: (res) => {
console.log(res.data);
}
});
出现的问题
::() -> () 一直都是false,然后用函数打印也一直都是GET。用内置浏览器和浏览器调试都没有问题,但是 一上真机就报错(提交方式错误)。
问题解决过程
网上查的是需要在后端添加下面的代码。原因是因为跨域了
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');
}
}
中添加下面代码
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'xmlhttprequest'
},
最后我尝试了上面的方法是无效的。
最终解决
最后我发现我的是因为https和http的原因,找了好久才找到。
最后将url: '#39;中http改为https即可
注意点: 我的服务器是开了强制HTTPS。