I am using +layout.server.ts to redirect unauthenticated users from accessing authorized routes with this code:
/* +layout.server.ts */
export const load: PageServerLoad = async () => {
// ...
if (!isAuthenticatedUser && isAccessingAuthorizedRoute) {
throw redirect(300, "/sign-in");
}
}
Run Code Online (Sandbox Code Playgroud)
But when I tested it by accessing an authorized url (let's say /user/profile), the browser gave me this error:
I didn't know what was the problem. After some workarounds and debugging, I found out the error was caused by server-side rendering. Because when I turned off the SSR in +layout.server.ts, redirect worked as expected and browser didn't throw any error. To confirm it, I also tried disabling SSR for a single page and only that page was redirecting rightly.
I am using +layout.server.ts to redirect unauthenticated users from accessing authorized routes with this code:
/* +layout.server.ts */
export const ssr = false; // <= SSR is off
export const load: PageServerLoad = async () => {
// ...
if (!isAuthenticatedUser && isAccessingAuthorizedRoute) {
// Working!
throw redirect(300, "/sign-in");
}
}
Run Code Online (Sandbox Code Playgroud)
Why is this happening? I want to use redirect() without disabling SSR.
UPDATE: I also tried redirect() in +page.ts, +page.server.ts and +layout.ts. The same error also happened there when ssr was enabled. I don't think my client-side js code is responsible.
Saz*_*med 13
我发现了问题。罪魁祸首是我用于重定向的状态代码。
我提供了错误的状态代码300:
// ...
if (!isAuthenticatedUser && isAccessingAuthorizedRoute) {
// Wrong!
throw redirect(300, "/sign-in");
}
// ...
Run Code Online (Sandbox Code Playgroud)
提供状态代码307解决了问题:
// From Svelte Documentation
export function load({ locals }) {
if (!locals.user) {
// Correct!
throw redirect(307, '/login');
}
}
Run Code Online (Sandbox Code Playgroud)
现在,启用SSR后它可以正常工作。文档中没有解释为什么我必须使用状态代码307才能使其正常工作。我希望他们能在不久的将来对此进行解释。
| 归档时间: |
|
| 查看次数: |
8163 次 |
| 最近记录: |