php - 由于有问题的 405 错误而禁用 CORS
问题描述
的背景:
我创建了一个基于苗条的 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 网站运行了代码,但没有成功。
没有工作,这给我带来了很多麻烦,所以我只想永久禁用 CORS,因为它弊大于利。
我不知道问题出在哪里,错误的 httpClient 请求或 CORS 像平常一样痛苦。
如果有人可以提供帮助,请告诉我。
由于服务器限制,我正在运行 PHP 5.6,因此像 tuupola/cors 这样的中间件由于 PHP <7 而无法工作
一些错误:
Safari 抛出:加载资源失败:预检响应不成功
Chrome 抛出:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源“ http://localhost:8100 ”。响应具有 HTTP 状态代码 405。
Chrome 也会抛出: OPTIONS http://localhost/api/v2/update/status/ {ID} 405 (Method Not Allowed)
解决方案
发送带有响应的标头:
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
另请参阅苗条文档:https ://www.slimframework.com/docs/v3/cookbook/enable-cors.html