【发布时间】:2018-02-10 09:28:58
【问题描述】:
我使用 [Ionic + PHP] 为注册表单创建了一个应用程序,但遇到以下问题。
CORS 附加组件:已激活 - 当我在 http://localhost:8100/ionic-lab 中使用它时效果很好
CORS 附加组件:已停用 - 当我在 http://localhost:8100/ionic-lab 中使用它时,它无法正常工作,并且出现以下提到的错误。
下面我将解释我的文件中的代码。
remote-service.ts
constructor(public http: Http) {
this.headers = new Headers()
this.headers.append('Content-Type', 'application/json')
this.headers.append('Content-Type', 'application/x-www-form-urlencoded')
this.headers.append('Access-Control-Allow-Origin', 'http://localhost:8100')
this.headers.append('Access-Control-Allow-Credentials', 'true')
this.headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD')
this.headers.append('Access-Control-Allow-Origin', '*')
this.headers.append('Accept', 'application/json')
this.headers.append('Accept', 'application/x-www-form-urlencoded')
console.log('Hello RemoteServiceProvider Provider');
}
getAllUsers() {
let options = new RequestOptions({ headers: this.headers })
return this.http.get('http://haitutorial.com/HybridApp/listAllUsers.php', options)
.map(res => res.json());
}
getAllUsers() - 此函数将获取从特定 URL 注册的所有用户。
database.php
<?php
include('database.php');
header('Access-Control-Allow-Origin' , '*');
header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
header('Accept','application/json');
header('content-type','application/json');
$query = "SELECT * FROM `users` WHERE `status`='1' AND `delete_status`='0' ORDER BY `user_id` DESC";
$result = mysqli_query($con,$query);
$count = mysqli_num_rows($result);
$resultant_array = array();
if($count>0)
{
while($informations = mysqli_fetch_assoc($result))
{
$resultant_array[] = $informations;
}
print_r(json_encode($resultant_array));
}
else
{
$resultant_array[] = ["success"=> 200, "message"=> "No Data Found", "status_code"=>1 ];
echo $output = json_encode($resultant_array);
}
?>
getAllUsers() 中提到的上述 URL 在浏览器中有效,但是当放置在 Ionic 应用程序中时,它会显示以下错误。
跨域请求被阻止:同源策略不允许读取位于http://haitutorial.com/HybridApp/listAllUsers.php 的远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。
当我在浏览器中启用 CORS 插件 后,上述问题得到解决。但是当我在浏览器中禁用 CORS 插件 时,它会显示错误。
同样的错误同样出现在插入页面中。当我从 APP 插入数据时,它会重定向到列表页面,并且不会显示数据并告诉上述错误。
我还在 PHP 文件中添加了header()。但我无法找出错误。我需要在不使用浏览器中的插件之类的东西的情况下修复此错误,并且也需要在 APP 中成功运行。
【问题讨论】:
-
GET 请求自动更改为 OPTIONS 方法,这就是此错误的原因。请为我提供在响应到来时如何将
GETHTTP 调用保留为 GET 本身的解决方案。 -
从 ionic 中删除 Access-* 和 Accept 标头。这些只是服务器端
-
如何接受来自 ionic.我已经从标题中删除了 Access.* 但它不能解决我的请求@Suraj Rao
-
任何人都可以分享我的解决方案。由于过去 3 天我无法找到解决方案。非常迫切需要解决方案。
标签: php web-services http-headers ionic3 httpservice