You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10+Vite非Vue项目使用Axios报‘axios未定义’问题求助

解决Laravel 10 + Vite环境下Axios未定义的问题

在Laravel 10搭配Vite的项目中,不使用Vue.js,尝试通过Axios发起Ajax请求时,控制台报错“axios is not defined”。以下是相关代码及解决方案:

相关代码

视图文件

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

布局文件资源引入

@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';

问题原因

Vite默认使用ES模块加载资源,@vite输出的脚本是异步加载的。而视图中直接编写的<script>会在Vite脚本完成加载并挂载window.axios之前执行,因此会出现未定义错误。

解决方案

方案一:将自定义代码纳入Vite打包流程

  1. 在resources/js目录下新建custom.js文件,编写请求逻辑:
// JS文件中无法直接使用Blade语法,需先将路由地址传入全局变量
axios.get(window.scannRoute)
    .then(function(rep){
        console.log(rep);
    });
  1. 在app.js中引入这个文件:
import './bootstrap';
import './custom.js'; // 添加这行

import Alpine from 'alpinejs';

window.Alpine = Alpine;

Alpine.start();
  1. 在视图文件中定义全局路由变量(需放在@vite之后):
<script>
window.scannRoute = "{{route('scann','xxx')}}";
</script>

方案二:确保脚本在资源加载完成后执行

修改视图中的脚本,通过DOMContentLoaded事件确保在所有资源加载完成后再执行Axios请求:

<script>
document.addEventListener('DOMContentLoaded', function() {
    axios.get("{{route('scann','xxx')}}")
        .then(function(rep){
            console.log(rep);
        });
});
</script>

额外检查

确认项目已安装Axios,若未安装,执行以下命令:

npm install axios

内容的提问来源于stack exchange,提问作者Omega

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 16:19:59