cors - Lumen 8 CORS 问题 2020 年 12 月
问题描述
我对使用 Lumen 8 的 CORS 有疑问。
我已经创建了 CorsMiddleware.php =>
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
// 'Access-Control-Allow-Origin' => getenv('ACCESS_CONTROL_ALLOW_ORIGIN'),
// 'Access-Control-Allow-Methods' => getenv('ACCESS_CONTROL_ALLOW_METHODS'),
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS')) {
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
}
在我的 bootstrap/app.php 中添加了它
$app->routeMiddleware([
App\Http\Middleware\CorsMiddleware::class,
'auth' => App\Http\Middleware\Authenticate::class,
]);
我什至添加到我的 .htaccess
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Credentials "true"
但和其他人一样没用......
奇怪的是,邮递员可以访问我的路线!?但是我的本地应用程序不能...
你们有什么想法吗?
解决方案
对于 Cors 中间件,我认为你应该在 $app->middleware([]) 中添加它。这是我们之前在项目中所做的。
$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);
这$app->middleware([]}
是一个全局中间件,它确实非常有效,尤其是在处理 HTTP 请求时。
如果您想将中间件分配给特定的路由,您应该首先在 bootstrap/app.php 文件对$app->routeMiddleware()
. 主要'auth' => App\Http\Middleware\Authenticate::class,
是因为您处理路线而经过这里。因此,为了保护而进行身份验证。
推荐阅读
- android-studio - Android Spinner 将下拉文本方向设置为 RTL
- variables - 如何在计算机内存中存储和访问变量及其引用?
- android - Android Studio 关闭键盘并完成活动
- node.js - TypeError:_this._transport.sendEvent 不是函数
- java - 从 C 转换为 Java 的块合并排序未正确排序;是我重构指针的责任吗?
- jekyll - 如何在没有 XML 文件的情况下将 Blogger 站点导入 Jekyll?
- java - 从另一个活动中获取数据正在给出 RuntimeException
- mysql - MySQL 从另一个表值更新表
- ruby - 有没有办法打印由 ruby-net-ldap 发送到 LDAP 服务器的确切命令?
- c# - 缩小矩形以显示它在大原始图像中的样子