首页 > 解决方案 > Laravel 对 OPTIONS 请求的响应 405

问题描述

在 Laravel 中,我们必须通过中间件或其他方式来处理预检请求。就我而言,我做了很多,但从未解决!

这是我尝试过的,

public function handle($request, Closure $next) { return $next($request) ->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); }

我将它添加到kernel.php$middleware中的数组中

我使用laravel-cors库来处理 cors 但也不起作用

我在public/index.php文件顶部添加了以下代码,

if (isset($_SERVER["HTTP_ORIGIN"]) === true) {
    $origin = $_SERVER["HTTP_ORIGIN"];
    $allowed_origins = array(
        "https://tapesh.io",
        "http://tapesh.io",
        "http://my.tapesh.io",
        "http://panel.tapesh.io",
    );
    if (in_array($origin, $allowed_origins, true) === true) {
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: *');
        header('Access-Control-Allow-Headers: Content-Type, X-Auth-Type, Origin');
    }
    if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
        exit; // OPTIONS request wants only the policy, we can stop here
    }
}

另外,我检查了 apache 错误日志。错误是这样的,

[2018 年 12 月 7 日星期六 07:35:36.678676] [allowmethods:error] [pid 7902:tid 139855840466688] [客户端 84.417.45.0:4012] AH01623:客户端方法被服务器配置拒绝:'OPTIONS' 到 /home/main/domains /example.com/private_html/api

我用谷歌搜索了一下,发现要使用 apache 来处理这个问题,我应该将其添加Require all granted到我域的 Apache 2.4 配置文件中。我做了但没有工作!

我还必须说,在其他项目中,我使用了 laravel-cors库,它解决了我的问题。

我真是糊涂了!

标签: phplaravelapachelaravel-5cors

解决方案


尝试在您的 routes.php 文件中添加标题:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');

如果您愿意,可以添加更多 Allow-* 标头。但当然,我建议您在 routes.php 中问题的“在 public/index.php 中添加 cors 处理代码”部分中使用您的代码,因为这是一个更安全的选择


推荐阅读