首页 > 解决方案 > 预检请求未通过访问控制检查

问题描述

当它给出上述错误时,尝试从我的 Angular 8 Web 应用程序发出 JWT 授权的 json rest api 请求。已遵循所有合理的 CORS 配置步骤,然后将规则放宽到仍然无法正常工作的程度,我已向你们寻求帮助。

因此,就 CORS 配置而言,在我开始的 php 方面:

header("Access-Control-Allow-Origin: http://localhost:4200");
header("Content-Type: application/json;charset=utf-8");
header("Access-Control-Allow-Methods: OPTIONS, GET, PUT, POST, DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

我放松了一点:

header("Access-Control-Allow-Origin: *");
header("Content-Type: *");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: *");

但是后来我在 CORS 文档中读到 Access-Control-Allow-Headers 不允许 *,所以我恢复了该行。

目前我有:

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json, text/plain, */*");
header("Access-Control-Allow-Methods: OPTIONS, GET, PUT, POST, DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, X-Requested-With, Authorization");

我得到的错误是:

从源“ http://localhost:4200 ”访问“ http://localhost/api/controllers/asset.php/ ”处的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

这是来自调试工具 (Chrome) 中网络选项卡的请求的标头信息。

临时标题显示接受:application/json、text/plain、 /授权:承载 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOm51bGwsImF1ZCI6IlRIRV9BVURJRU5DRSIsImlhdCI6MTU2NjYyOTIxNywibmJmIjoxNTY2NjI5MjELCJle...red

这是在 apache 上运行 php 7.2

我希望新的宽松 CORS 设置能够工作,但我仍然收到此错误。

如何调整 CORS 设置以满足飞行前请求?

标签: phpangularrestcors

解决方案


我创建了一个名为Willow的框架。这是我使用的克服 CORS 疯狂的代码。

    $requestMethod = $_SERVER['REQUEST_METHOD'];

    // Is this a pre-flight request (the request method is OPTIONS)? Then start output buffering.
    if ($requestMethod === 'OPTIONS') {
        ob_start();
    }

    // Allow for all origins and credentials. Also allow GET, POST, PATCH, and OPTIONS request verbs
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, OPTIONS, DELETE');

    // If this is a pre-flight request (the request method is OPTIONS)? Then flush the output buffer and exit.
    if ($requestMethod === 'OPTIONS') {
        ob_end_flush();
        exit();
    }

高温高压


推荐阅读