Home

Issue: 2022

How to force a redirect to the 404 error page?

[issue link]

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)