LoginSignup
6
6

More than 3 years have passed since last update.

【エラー】Nuxt.jsとLaravelのAPIでajax通信した際のCORSエラー

Posted at

概要

現在、Nuxt.jsからLaravelで作ったAPIにaxiosライブラリで通信しようとしたら、以下のようなエラーが出た。

スクリーンショット 2019-12-16 17.40.37.png

エラー前のコード

Nuxt.js自体をhttp://localhost:3000で起動。

index.Vue

        methods: {
            get_text(){
                this.$axios.$get("/index")
                .then((response)=>{
                    this.text = response
                })
                .catch((error)=>{
                console.log(error.name + ": " + error.message);
                })
            }
        }

nuxt.config.js


  axios: {
    baseURL: 'http://localhost:8000/api'
  }

原因

いわゆるCORS(Cross-Origin Resource Sharing)エラー。

僕の解釈ですが、以下が必要だと思います。

・信頼性のないドメインを排除するために出たエラー
・Ajax通信する際は、ドメインが同じである必要性

今回僕のコードでは、
http://localhost:3000 → http://localhost:8000と、異なるドメインに対してAjax通信しようとしています。

nuxt.config.jsを以下のように修正しました、プロキシを設定します。

修正後のコード

index.Vue

        methods: {
            get_text(){
                this.$axios.$get("/api/index") // 修正
                .then((response)=>{
                    this.text = response
                })
                .catch((error)=>{
                console.log(error.name + ": " + error.message);
                })
            }
        }

nuxt.config.js


  axios: {
    proxy: true  // 追加
  },
  proxy: {
    '/api': 'http://localhost:8000', // 追加
  },

6
6
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
6
6