LoginSignup
0

More than 3 years have passed since last update.

モバイル環境でNetwork Errorでハマった。「EC2にDocker Caddy Laravel, S3にVuejsの構成」

Posted at

指摘などウェルカムです。
クロスオリジン(CORS)に関連するエラーなんだと思うけどPCでは動くが、携帯 IOS Iphone7(古い)からのブラウザ(最新)ではsafariもchromeも動かないって現象で結構ハマった。

環境

大体の構成
route53から分岐
-> CloudFront+S3にvuejs
-> ALBからEC2(Ubuntu)にDocker Caddy Laravel

解決策

サーバー側のクロスオリジンの設定をちゃんと設定する。

Access-Control-Allow-Origin
Access-Control-Allow-Headers
をざっくり設定して * としていた。
これが原因だった。
ちゃんとフロントs3側のホスト名を指定したら動いた。
この記事で必須と書いてあるので、ん?と思って設定したら動いた。

:OK.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
  public function handle($request, Closure $next)
  {
    return $next($request)
      //ちゃんとホスティングしてるs3のドメインを指定
      ->header(Access-Control-Allow-Origin, https://hoge.s3.com)
      ->header(Access-Control-Allow-Methods, GET, POST, PUT, DELETE, OPTIONS)
      ->header(Access-Control-Allow-Headers, X-Requested-With, Content-Type, X-Token-Auth, Authorization);
  }
}
駄目.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
  public function handle($request, Closure $next)
  {
    return $next($request)
      ->header(Access-Control-Allow-Origin, *)
      ->header(Access-Control-Allow-Methods, GET, POST, PUT, DELETE, OPTIONS)
      ->header(Access-Control-Allow-Headers, X-Requested-With, Content-Type, X-Token-Auth, Authorization);
  }
}

調べた履歴

Laravelのルーティングについて結構大事だと思う。
axiosでget, post以外にoptionも使うのでルーティング注意。

Route::match(['options', 'patch']'/{test_id}', 'TestController@update');
Route::match(['options', 'delete'], '/{test_id}', 'TestController@destroy');

CORSを許可したLaravel製APIサーバーでput, patch, deleteが出来なくて泣いてたけど、ようやく解決出来た話

CSRFが問題か?
X-Requested-Withヘッダか?

Laravel/Vue SPAs: How to send AJAX requests and not run into CSRF token mismatch exceptions
https://medium.com/@serhii.matrunchyk/laravel-vue-spas-how-to-send-ajax-requests-and-not-run-into-csrf-tokens-mismatch-exceptions-da3b71b287ab
https://www.techalyst.com/posts/vuejs-axios-laravel-x-csrf-token-x-xsrf-token-csrf-protection

axiosが悪いのか?
https://qiita.com/terrierscript/items/ccb56b6fc05aa7821c42

crossのエラーぽいが。
https://stackoverflow.com/questions/50873764/cross-origin-read-blocking-corb
https://stackoverflow.com/questions/38749605/cors-access-control-allow-origin-on-laravel
https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-get-a-no-access-control-allow-origin-header-is-pr
https://github.com/laravel/framework/issues/13643
https://medium.com/@petehouston/allow-cors-in-laravel-2b574c51d0c1

サーバの.htaccessが悪いのか?
https://forum.laragon.org/topic/1435/access-control-allow-origin-is-already-set/6

モバイルではそもそも動かないのか?

Axios doesn't work with Android (emulator) raising a Network Error
https://github.com/axios/axios/issues/973

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0