重新導向

當您手動或透過 <Link> 元素發出非 GET 的 Inertia 請求時,您應該確保您始終回應正確的 Inertia 重新導向回應。

例如,如果您的控制器正在建立新使用者,您的「store」端點應返回重新導向到標準 GET 端點(例如您的使用者「index」頁面)。Inertia 將自動跟隨此重新導向並相應地更新頁面。

class UsersController extends Controller
{
    public function index()
    {
        return Inertia::render('Users/Index', [
            'users' => User::all(),
        ]);
    }

    public function store(Request $request)
    {
        User::create(
            $request->validate([
                'name' => ['required', 'max:50'],
                'email' => ['required', 'max:50', 'email'],
            ])
        );

        return to_route('users.index');
    }
}

303 回應碼

當在 PUTPATCHDELETE 請求後重新導向時,您必須使用 303 回應碼,否則後續請求將不會被視為 GET請求。303 重新導向與 302 重新導向非常相似;但是,後續請求會明確變更為 GET 請求。

如果您正在使用我們的官方伺服器端介面卡之一,所有重新導向都將自動轉換為 303 重新導向。

外部重新導向

有時需要將 Inertia 請求處理時重新導向到外部網站,甚至是應用程式中的另一個非 Inertia 端點。這可以使用伺服器端發起的 window.location 透過 Inertia::location() 方法進行訪問。

return Inertia::location($url);

Inertia::location() 方法將產生 409 Conflict 回應,並在 X-Inertia-Location 標頭中包含目標 URL。當在客戶端收到此回應時,Inertia 將自動執行 window.location = url 訪問。