redirect
這是傳送 30x 回應的快捷方式。
import { redirect } from "@remix-run/node"; // or cloudflare/deno
export const action = async () => {
const userSession = await getUserSessionOrWhatever();
if (!userSession) {
return redirect("/login");
}
return json({ ok: true });
};
預設情況下,它會傳送 302,但您可以將其變更為您想要的任何重新導向狀態碼
redirect(path, 301);
redirect(path, 303);
您也可以傳送 ResponseInit
來設定標頭,例如提交 session。
redirect(path, {
headers: {
"Set-Cookie": await commitSession(session),
},
});
redirect(path, {
status: 302,
headers: {
"Set-Cookie": await commitSession(session),
},
});
當然,如果您喜歡自己建立,您也可以在沒有此輔助程式的情況下進行重新導向
// this is a shortcut...
return redirect("/else/where", 303);
// ...for this
return new Response(null, {
status: 303,
headers: {
Location: "/else/where",
},
});
而且您可以拋出重新導向來中斷呼叫堆疊並立即重新導向
if (!session) {
throw redirect("/login", 302);
}