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

如何修改Inertiajs Router默认请求目标为api.php(Vue应用)

修改Inertia.js Vue应用的默认请求目标为api.php

要让Inertia.js的Router默认请求Laravel的api.php路由文件,只需在Vue端初始化Inertia时配置全局的baseURL即可,具体步骤如下:

1. 配置Vue端的Inertia基础URL

在你的Vue应用入口文件(通常是resources/js/app.js或main.js)中,修改createInertiaApp的配置,添加router选项并设置baseURL为/api:

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'

createInertiaApp({
  resolve: name => import(`./Pages/${name}`),
  // 新增Router配置,指定默认请求的基础URL
  router: {
    baseURL: '/api',
  },
  setup({ el, App, props, plugin }) {
    return createApp({ render: () => h(App, props) })
      .use(plugin)
      .mount(el)
  },
})

2. 调整请求代码

配置完成后,你无需在每个请求路径前手动添加/api,直接写路由的相对路径即可:

await router.post(
  "/guardian-app/m/verify-phone",
  {}
)

此时Inertia会自动拼接基础URL,最终请求地址为/api/guardian-app/m/verify-phone,与你提供的PHP路由完全匹配:

Route::post('/api/guardian-app/m/verify-phone', [GuardianPhoneVerificationController::class, 'verifyPhone']);

注意事项

  • 如果你的应用同时需要访问web.php中的路由(比如页面跳转),可以在页面跳转时手动指定完整路径,或者针对不同请求类型单独配置。
  • 确保api.php中的路由中间件组能处理Inertia请求:如果需要使用会话(Session),需在api中间件组中添加web中间件(不推荐无状态API场景);如果是无状态API,直接使用默认的api中间件组即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:40:03