php - Laravel 对 OPTIONS 请求的响应 405
问题描述
在 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 错误日志。错误是这样的,
[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库,它解决了我的问题。
我真是糊涂了!
解决方案
尝试在您的 routes.php 文件中添加标题:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
如果您愿意,可以添加更多 Allow-* 标头。但当然,我建议您在 routes.php 中问题的“在 public/index.php 中添加 cors 处理代码”部分中使用您的代码,因为这是一个更安全的选择
推荐阅读
- reactjs - 如何在 POST 后使用 fetch in react 获取 ID 并将其显示在警报框中
- docker - AzerothCore docker installation stucks at connected
- github - Github API: How to do user authentication with the javascript API?
- r - 在 R 中粘贴两列,但 NA 包含在新列中
- android-studio - Android Studio ArticFox 编译正常但到处显示红色错误
- sql - 链接名称和名字的子查询 SQL
- javascript - 在几秒钟内给 Tone.js 音符和持续时间数组播放的最简单方法是什么?
- vue.js - 使用 nuxtjs/svg 动态导入 SVG
- database - MongoDB - 将聚合/查询结果存储在单独的集合中
- extjs - 如何在 ExtJs 中单击 TabPanel 中的 Tab 菜单时初始化各个选项卡数据?