【Laravel】axiosを使った非同期通信が404になる

エラー内容

レスポンス:

AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST',

 

考えられる原因:

  • ルーティングを間違えている
  • 通信先のURLが間違えている

 

404になる原因

Routeの設定を行っているのにレスポンスがになってしまう。

解決方法はエラーの文言通り、ページが存在していない事が原因です。

エラーになるコード

routes/api.php

Route::get(
    '/test',
    [Test::class, 'test_function']
);

 

resources/js/components/EnduserSearchstore.vue

import axios from 'axios';

    export default {
        data() {
            return {
                users: {},
            }
        },
        methods: {
            getBigCategory() {
                axios.get('/api_search_storeCategory')
                    .then((response) => {
                        // this.users = response.data.users
                        response(console.log(response))
                    })
            }
        },
        created() {
            this.getBigCategory()
        }
    }

 

 

正常動作するコード

routes/api.php

Route::get(
    '/test',
    [Test::class, 'test_function']
);

 

resources/js/components/EnduserSearchstore.vue

import axios from 'axios';

    export default {
        data() {
            return {
                users: {},
            }
        },
        methods: {
            getBigCategory() {
                axios.get('/api/test')
                    .then((response) => {
                        // this.users = response.data.users
                        response(console.log(response))
                    })
            }
        },
        created() {
            this.getBigCategory()
        }
    }

 

 修正内容

axiosでURLを指定している箇所を「axios.get('/api/test')」と指定してあげる。

Laravelでは、route/api.phpで指定したルーティングではデフォルトで接頭辞に「/api」が付くことになっているっぽいです。
そのため、エラーになるコードではVue側で呼び出しているURLは存在しない遷移先となっています。

LaravelのAPIのルーティングはデフォルトが付くのを忘れないようにしましょう〜。

Twitterでフォローしよう

読んでみーな
おすすめの記事