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

Laravel+Vue中Inertia重定向异常:请求成功但页面不跳转

解决Inertia+Vue3中AJAX请求后重定向不更新页面的问题

问题原因

普通axios发送的AJAX请求不属于Inertia请求(未携带X-Inertia请求头),后端返回的Inertia::location()仅在Inertia请求上下文里才会被客户端处理。浏览器虽会自动跟随AJAX的302重定向,但该过程在后台完成,不会触发页面URL更新和组件渲染。

解决方案

方案1:改用Inertia的请求方法(推荐)

直接使用Inertia提供的post方法发起请求,它会自动携带Inertia标识头,后端的重定向指令会被正确处理:

<script setup>
import { useInertia } from '@inertiajs/vue3'
const { post } = useInertia()

const createChat = async () => {
  try {
    await post('/chat/create', {
      // 填入你的请求参数,比如title、participants等
    })
  } catch (err) {
    // 处理错误,比如表单验证失败提示
    console.error(err)
  }
}
</script>

后端控制器代码无需修改:

public function createChat(Request $request)
{
    // 验证请求参数
    $validated = $request->validate([
        // 你的验证规则
    ]);
    
    // 创建Chat实例
    $chat = Chat::create($validated);

    return Inertia::location(route('chat.show', $chat));
}

方案2:保留axios,调整前后端逻辑

如果必须使用axios,需要后端返回JSON格式的重定向URL,前端手动触发页面导航:

后端修改:

public function createChat(Request $request)
{
    $validated = $request->validate([
        // 验证规则
    ]);
    
    $chat = Chat::create($validated);

    return response()->json([
        'redirect_url' => route('chat.show', $chat)
    ]);
}

前端修改:

import axios from 'axios'
import { useRouter } from '@inertiajs/vue3'

const router = useRouter()

const createChat = async () => {
  try {
    const res = await axios.post('/chat/create', {
      // 请求参数
    })
    
    // 使用Inertia路由导航,保持SPA体验
    await router.visit(res.data.redirect_url)
    
    // 若不需要SPA特性,也可以直接跳转
    // window.location.href = res.data.redirect_url
  } catch (err) {
    console.error(err)
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:55:08