I've dynamic route http://localhost:3000/sections/slug-name
. I want to display or redirect to the 404 page if the URL is invalid. trying to do something like this but with the fetch method.
I know we can do <p v-if="$fetchState.error">404 Invalid Section</p>
but is there any better way to show 404 page.
following is my code for your reference
<script>
export default {
data() {
return {
posts: {},
loader: false,
}
},
head() {
return {
title: this.posts.category_name ,
}
},
methods: {
getResults(page = 1) {
if (this.$route.query.page != page) {
this.$router.push({
query: {
page: page,
},
})
}
},
loadPosts(page) {
this.loader = true
this.$axios
.$get(`category/${this.$route.params.category}?page=${page}`)
.then((response) => {
this.posts = response
this.loader = false
})
},
},
watch: {
$route(to, from) {
this.loadPosts(to.query.page)
},
},
async fetch() {
let page = this.$route.query.page ? this.$route.query.page : 1
this.posts = await this.$axios
.$get(`category/${this.$route.params.category}?page=${page}`)
.catch((e) => {
this.$router.push({ name: 'fallback-page' })
})
},
}
</script>
Update: as shown in my answer here, you can use this if you want the same behavior while using the fetch()
hook
this.$nuxt.context.error({
status: 500,
message: 'Something bad happened',
})
Since you're using SSR, the part below is mostly wrong.
If you don't have a route for a specific path, you could setup this
nuxt.config.js
export default {
generate: {
fallback: '404.html',
},
}
and create a /layouts/error.vue
file
<template>
<p>some error here {{ error }}</p>
</template>
<script>
export default {
props: ['error'],
}
</script>
Thay way, if you reach upon /hello-word
while it doesn't exist in your route, you will fallback to this one.
As explained here and here.
If you want a client side redirect after your fetch, you could always have a
.catch((e) => { this.$router.push({ name: 'fallback-page' }) })
after a catch
.
you must use error({ statusCode: 404})
in catch
of fetch or asyncData method to redirect client to 404 page
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With