Nuxt.js: How to force a redirect to the 404 error page?

Created on 3 Nov 2017  路  5Comments  路  Source: nuxt/nuxt.js

I have a page where some data is fetched in the mounted method.

When the async result is checked, I want to redirect the page to the layout/error.vue 404 page.
How can you force nuxt to redirect with an error status?

The code that needs to do the redirection:

export default {
    data() {
        return {
            post: null,
        };
    },

    mounted() {
        this.getPost(); // Fetch the post data from the server
    },

    methods: {
        async getPost() {
            return await axios.get(`${config.api.baseUrl}/posts/${this.$route.params.postId}`)
                .then(response => {
                    this.post = response.data;
                    if (this.post.error) {
                        //FIXME Display a 404
                        console.log(`-------> Error getting this post id`); //DEBUG
                    }
                },
                      error => { // Response handler (rejected)
                          console.error(`Impossible to fetch the post data. Please try again in a moment.`, error);
                      });
        },
    },
};

I tried checking the validate method, but can't see how to mix my async call in there.

This question is available on Nuxt.js community (#c1796)

Most helpful comment

Hi, you should use Async Data, check Handling Errors section

All 5 comments

I tried using:

async validate({ params }) {
    const postData = await axios.get(`${config.api.baseUrl}/posts/${params.postId}`);
    this.post = postData;
    if (postData.error) {
        console.log(`An error has been found!`, postData); //DEBUG
        return false;
    }

    return true;
},

but the redirect is not done.

Hi, you should use Async Data, check Handling Errors section

@AlexandreBonneau got answer for you (and maybe others):

Seems it's WordPress REST API behavior and actually it's not a nuxt problem.

When you requesting WP API for post that actually not exist in response you getting just empty array (not 404 error).

Try to rehandle your error:

async asyncData ({ store, $axios, params, error }) {
  return $axios.get(`${store.state.api}/wp/v2/catalog`, {
    params: {
      _embed: true,
      slug: params.slug
    }
  }).then(item => {
    if (item.data.length === 0) throw({ statusCode: 404, message: 'Post not found' })
    return { item: item.data[0] }
  }).catch(e => {
    error(e)
  })
}

With try ... catch ... it works well too. :)

If you want to force a redirect to the 404 page you can return a $nuxt error like this:

try {
  // Some API request
} catch (err) {
  if (err.response.status === 404) {
    return this.$nuxt.error({ statusCode: 404, message: err.message })
  }
}

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vadimsg picture vadimsg  路  3Comments

vadimsg picture vadimsg  路  3Comments

msudgh picture msudgh  路  3Comments

shyamchandranmec picture shyamchandranmec  路  3Comments

uptownhr picture uptownhr  路  3Comments