在Lumen API上启用CORS



我知道这是一个已知的问题,但我已经尝试了几乎所有的方法,但我仍然坚持这个问题。我有一个简单的项目结构如下:

[Client]       =>     [Gateway]       =>      [API] 
Laravel 6              Lumen 6               Lumen 6
localhost:8000         localhost:8001       localhost:8002

因为我刚开始做这个项目只是为了证明它是否有效,所以我禁用了所有auth的东西。

在我的API上我在public中有一个名为uploads的文件夹(基本上在http://localhost:8002/uploads/audio.amr中(,其中我有一个音频文件(.amr(,我正在尝试从客户端视图播放它。

由于html不能播放.amr文件,我不得不使用插件。我用的是这个BenzAMRRecorder。

[客户端]我做了一个ajax请愿书来获取音频文件的url。客户端通过guzzle连接网关门户也通过API连接,我成功获得了urlhttp://localhost:8002/uploads/audio.amr

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : 'client/get_url_audio',
type : 'GET',
data : {
},
dataType:'json',
success : function(data) {
/** Here's the way to play the file */
var amr = new BenzAMRRecorder();
amr.initWithUrl(data['url']).then(function() {
amr.play();
});
},
});

我成功地获得了url,但当BenzAMRRecorder尝试访问urlhttp://localhost:8002/uploads/audio.amr时,我收到了以下错误:

错误:

访问'XMLHttpRequesthttp://localhost:8002/uploads/audio.amr'来自原点'http://localhost:8000'已被CORS策略阻止:请求的资源上不存在"Access Control Allow Origin"标头。

我已经阅读了很多修复此问题的方法,并在API上添加了一个CorsMiddleware,其句柄函数如下:

public function handle($request, Closure $next)
{
$headers = [
'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->middleware([
AppHttpMiddlewareCors::class
]);

但我还是犯了同样的错误。我的想法是,当方法amr.initWithUrl(data['url'])访问API文件夹时,它不会进入中间件,而是尝试在不经过中间件的情况下直接访问文件夹,但我不知道为什么。有人能帮我解决这个问题吗?

编辑:我也试过github.com/barryvdh/laravel-cors

在服务器的.htaccess文件中添加以下内容,该文件包含您试图访问的资源:

Header Set Access-Control-Allow-Origin "*"

我不知道它是否在Lumen中有效,但对于Laravel来说,我使用这个neomerx/cors包取得了很大成功。

您可能错过了CORS中间件的头X-CSRF-TOKEN

$headers = [
....
// You will need to add ALL headers sent from your client
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With, X-CSRF-TOKEN'
];

最新更新