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

Vue Router与Laravel 8路由兼容问题:404错误求助

解决Laravel 8 + Vue Router 404问题

问题根源分析

  1. Laravel路由路径错误:在accounts前缀的路由组里,你定义的兜底路由是/accounts/{any},加上前缀后实际路径变为/accounts/accounts/{any},和Vue Router配置的路径完全不匹配。
  2. 缺少全局兜底路由:Vue Router使用createWebHistory()(HTML5 history模式)时,除根路径外的其他路径刷新会直接请求Laravel服务器,此时需要Laravel返回Vue入口视图,让Vue Router接管路由处理。

修正步骤

1. 调整Laravel Web路由配置

把错误的兜底路由移出accounts前缀组,改成全局兜底路由,确保所有非API、非静态资源的GET请求都返回Vue入口视图(假设你的Vue入口视图是welcome.blade.php):

Route::get('/', function() {
    return view('welcome');
});

// 保留账号相关的API接口路由
Route::prefix('accounts')->group(function(){
    Route::post('register', [AuthController::class, 'register'])->name('register');
    Route::post('login', [AuthController::class, 'login'])->name('login');
});

// 全局兜底路由:处理所有Vue Router的前端路径请求
Route::get('/{any}', function () {
    return view('welcome');
})->where('any', '.*');

2. 确认Vue Router挂载正常

确保你的Vue实例已经正确挂载了路由配置(比如在resources/js/app.js中):

import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // 引入你的路由文件

createApp(App).use(router).mount('#app')

3. 生产环境服务器配置(可选)

如果部署到生产环境,需要配置Web服务器重写规则,把所有请求转发到Laravel的index.php:

  • Nginx:在server块中添加
location / {
    try_files $uri $uri/ /index.php?$query_string;
}
  • Apache:确保mod_rewrite模块开启,public/.htaccess保留Laravel默认的重写规则即可:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

验证操作

  1. 清除Laravel路由缓存:执行php artisan route:clear
  2. 重启本地开发服务器(若使用php artisan serve)
  3. 访问/accounts/signin、/accounts/signup和/,确认页面正常渲染,不再返回404错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:23:10