我知道这是一个众所周知的问题,但我几乎尝遍了所有方法还是没有解决。我有一个结构简单的项目,如下所示:
[Client] => [Gateway] => [API]
Laravel 6 Lumen 6 Lumen 6
localhost:8000 localhost:8001 localhost:8002
因为我刚刚才开始做这个项目,目前我已经禁用了所有东西。
在我的API中,有一个叫做UPATADS(在 http://localhost:8002/uploads/audio.amr 中)的文件夹,其中有一个音频文件(.amr),我正试图从客户端视图中播放它。
因为html不能播放.amr文件,所以我不得不使用插件,我用的是这个BenzAMRRecorder(https://www.npmjs.com/package/amr-js)。
我发出了一个Ajax请求以获取音频文件的url,客户端通过GUSOST与网关连接,网关也使用API进行连接,然后我成功获得了url:http://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尝试访问url(http://localhost:8002/uploads/audio.amr)时得到了错误提示:
Access to XMLHttpRequest at 'http://localhost:8002/uploads/audio.amr' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我已经阅读了很多修复这个问题的方法,我还在API上添加了一个Cors中间件,如下所示:
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([
App\Http\Middleware\Cors::class
]);
但还是得到同样的错误。我奇怪的是,当方法amr.initWithUrl(data['url']访问API文件夹时,它不会直接访问这些文件夹,反而要经过中间件——我不知道为什么。有人能帮我解决这个问题吗?
更新:我也试了下这个: github.com/barryvdh/laravel-cors。