Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create 404 page on dynamic routes Nuxt js Fetch method

Tags:

vue.js

nuxt.js

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>
like image 435
Kunal Rajput Avatar asked Oct 17 '25 06:10

Kunal Rajput


2 Answers

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.

like image 184
kissu Avatar answered Oct 19 '25 20:10

kissu


you must use error({ statusCode: 404}) in catch of fetch or asyncData method to redirect client to 404 page

like image 44
Keyvan Gholami Avatar answered Oct 19 '25 19:10

Keyvan Gholami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!