【发布时间】:2018-11-17 04:38:18
【问题描述】:
背景:
我创建了一个基于精简的 API,目前在本地域运行,例如 localhost/api
我有一个使用 ionic 框架(基于 angular)的移动应用程序,并且有以下代码使用 httpClient 作为 http:
let accessurl = this.general.apiURL + '/v2/update/status/' + this.machineToChange;
const headers = new HttpHeaders()
.set('Authorization', 'Bearer: ' + this.general.apiKey);
this.http.put(accessurl, {
statusFuelled: 1
}, { headers: headers }).subscribe(result => {
console.log(JSON.stringify(result));
}, err => {
console.log(JSON.stringify(err));
});
我已经尝试了所有我能找到的让超薄框架禁用 cors 的堆栈溢出问题,这里只是几个:
$app->options('/update/status/{machineNo}', function ($request, $response) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
return $response->withStatus(200);
});
或者:
//http://stackoverflow.com/questions/18382740/cors-not-working-php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
或者:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header('Content-Type: application/json');
或者在.HTACCESS中:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header add Access-Control-Allow-Headers: Content-Type
还有更多使用 composer 的中间件。
我还从Slim Website 运行了代码,但没有成功。
没有工作,这给我带来了很多麻烦,所以我只想永久禁用 CORS,因为它弊大于利。
我不知道问题出在哪里,错误的 httpClient 请求或 CORS 像平常一样痛苦。
如果有人可以帮忙,请告诉我。
由于服务器限制,我正在运行 PHP 5.6,所以像 tuupola/cors 这样的中间件由于是 PHP
一些错误:
Safari 抛出:加载资源失败:预检响应不成功
Chrome 抛出:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:8100' 不允许访问。响应的 HTTP 状态代码为 405。
Chrome 也会抛出:OPTIONS http://localhost/api/v2/update/status/{ID} 405(不允许的方法)
【问题讨论】:
-
Htaccess 明显缺失
header('Content-Type: application/json');Access-Control-Allow-Headers: Content-Type -
嗨 Swoox,Content-Type 标头在完成成功或不成功的请求时发送,使用
$response->withStatus(200)->withHeader("Content-Type","application/json");所以我假设你在其他地方不需要它 -
你在 htaccess 中需要这个:
Access-Control-Allow-Headers: Content-Type不要像我的系统管理员那么固执,我跟他说了 5 次,然后勉强做到了。 -
我已经添加了 Swoox 但仍然没有运气,chrome 正在抱怨“Access-Control-Allow-Origin”标头,所以我猜这就是问题所在。
-
查看大安的答案。
标签: php angular ionic-framework cors slim