简体   繁体   中英

Using Sapper, how can I redirect to the index page on a 404 error?

On a 404 error, I don't want to display a 404 page. Instead, I'd like to redirect back to the index page if the user is logged in or to the login page if the user is logged out. I'm already able to route the user to the login in page from the index page if not signed in, so I may just need to redirect to the index page and have it take care of the reroute to the login in page, although that seems inefficient to have to do two reroutes.

I'm able to accomplish it by re-writing the routes/_error.svelte page to this...

<script>
    import { onMount } from 'svelte';
    onMount(() => {window.location.href = '/'});
</script>

But I'm not very confident it's the best way to accomplish what I want to do. It also redirects for all errors, and in a future project, I may want to show certain errors such as 404, but redirect on other errors like 500.

Does anyone have some insight on how this might be better accomplished using Sapper?

You should try goto function.

import { goto } from '@sapper/app';
goto('your/path');

and if you want to do it in the onMount hook, it should be:

<script>
    import { onMount } from 'svelte';
    import { goto } from '@sapper/app';
    onMount(() => goto('your/path'));
</script>

In your very specific case, if you want to do it on an error criteria on the _error.svelte page, you should choose your path depending on error:

<script>
    import { onMount } from 'svelte';
    import { goto } from '@sapper/app';
    onMount(() => goto(
      error.status === 500
        ? 'path1'
        : error.status === 404
        ? 'path2'
        : 'path3'
    ));
</script>

original GitHub issue here

You can also use the HTML meta tag to redirect. Use it on routes/_error.svelte like this:

<svelte:head>
    <meta http-equiv="refresh" content="0; URL=./index" />
</svelte:head>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM