weixin_33749131 2020-02-27 21:57 采纳率: 0%
浏览 109

如何在 Lumen API 上启用 CORS?

我知道这是一个众所周知的问题,但我几乎尝遍了所有方法还是没有解决。我有一个结构简单的项目,如下所示:

                [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。

  • 写回答

3条回答 默认 最新

  • bug^君 2020-02-27 22:10
    关注

    Add the following in the .htaccess file from the server which holds the resource you are trying to access:

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

报告相同问题?

悬赏问题

  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面