laravelnpmaxiosvite

How to use Axios with Laravel 10 and Vite?


I want to make an Ajax call using Axios in Laravel 10 with Vite (I don't use VueJs). I get the error "axios is not defined".

My view :

<x-app-layout>
   

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
            <div class="p-4 sm:p-8 bg-white dark:bg-gray-800 shadow sm:rounded-lg">
                hello world
            </div>
            
        </div>
    </div>

    <script>
            axios.get("{{route('scann','xxx')}}"
            ).then(function(rep){
                console.log(rep)
            })
        
    </script>
</x-app-layout>

in the layout I have included css and js before closing header with : @vite(['resources/css/app.css', 'resources/js/app.js'])

app.js :

import './bootstrap';

import Alpine from 'alpinejs';

window.Alpine = Alpine;

Alpine.start();

bootstrap.js :

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

import axios from 'axios';
window.axios = axios;

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Solution

  • It's likely that app.js isn't loaded until after the script tag in your view (Vite scripts are type="module" by default, so loading is deferred). Try waiting until the DOM is loaded:

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            axios.get('/some-endpoint')
                .then(response => console.log(response))
                .catch(error => console.error(error));
        });
    </script>