0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CORSについて

Last updated at Posted at 2020-09-27

dockerでnuxtとlaravelのコンテナを作成した際の話。

やっていたこと

nuxtからlaravelに向かってリクエストを送ったがエラーが発生。

Access to XMLHttpRequest at 'http://0.0.0.0:23450/api/register' from origin 'http://0.0.0.0' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

corsポリシーに反しているから、ブロックしたぞと言われている。
corsで調べると「別々のoriginがやりとりできるようにすること」だとか。
originとはドメイン+ポート+urlのこと。
https://developer.mozilla.org/ja/docs/Web/HTTP/CORS

解決方法

laravel側で受け取れるようにmiddlewareを設定する。
参考はCORSについて理解してLaravel5.6で対応する

自作のmiddlewareを作成して、全てのrouteで発動させる


<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    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', 'Content-Type');
    }
}

やってみたけど、うまくいかなかったこと

・nuxt側でproxyという機能を使ったcorsの設定
Vue.jsとAPIサーバとのaxiosでCORSに引っかかった時のProxyを使った回避方法

【Nuxt.js】データベースにCORSで接続できない?ならば @nuxtjs/proxy を使いなさい【手順】

原因解明

baseURL、browserBaseURLの設定が必要だった模様。
参考:
【解決済】Docker上のNuxtでaxiosのCORSエラーにハマりまくった話
baseurl
browserbaseurl

corsの勉強になった参考文献

CORSについて理解してLaravel5.6で対応する
CORSまとめ
【Rails6】Gem rack-corsを導入してCORS設定を行う(オリジン・CORSとは何か)
CORS を分かってないから動くコード書いて理解する
Preflight request (プリフライトリクエスト)

0
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?