【发布时间】:2019-05-09 21:10:28
【问题描述】:
在 Laravel 中,我们必须通过中间件或其他方式处理预检请求。就我而言,我做了很多,但从未解决!
这是我尝试过的,
-
中间件处理
在这种情况下,我确实创建了一个新的中间件并将此代码作为
handle方法。
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
我使用 laravel-cors 库来处理 cors,但也不起作用
- 在 public/index.php 中添加 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 配置
另外,我检查了 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
我用 google 搜索了一下,发现要使用 apache 来处理这个问题,我应该将 Require all granted 添加到我的域的 Apache 2.4 配置文件中。我做了但没有工作!
我还必须说,在其他项目中,我使用了 laravel-cors 库,它解决了我的问题。
我真的很困惑!
【问题讨论】:
-
该错误确实表明问题是 apache 配置问题。通过this page仔细确保你已经涵盖了所有可能的情况。如果启用,其他模组的链接(例如mod_allowmethods)也可能导致此问题。
-
我已经这样做了!我将解决方案放在 .htaccess 和用户 httpd.conf 文件中。但它没有用!另外,我不是 apache 配置方面的专家! @apokryfos
标签: php laravel apache laravel-5 cors