redirect
这是发送 30x 响应的快捷方式。
¥This is a shortcut for sending 30x responses.
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,但你可以将其更改为你想要的任何重定向状态码:
¥By default, it sends 302, but you can change it to whichever redirect status code you'd like:
redirect(path, 301);
redirect(path, 303);
你还可以发送 ResponseInit
来设置标头,例如提交会话。
¥You can also send a ResponseInit
to set headers, like committing a session.
redirect(path, {
headers: {
"Set-Cookie": await commitSession(session),
},
});
redirect(path, {
status: 302,
headers: {
"Set-Cookie": await commitSession(session),
},
});
当然,如果你想自己构建,也可以不使用这个辅助函数进行重定向:
¥Of course, you can do redirects without this helper if you'd rather build it up yourself:
// this is a shortcut...
return redirect("/else/where", 303);
// ...for this
return new Response(null, {
status: 303,
headers: {
Location: "/else/where",
},
});
你可以抛出重定向来突破调用堆栈并立即重定向:
¥And you can throw redirects to break through the call stack and redirect right away:
if (!session) {
throw redirect("/login", 302);
}