Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt.js and handle API 404 response for dynamic pages

Tags:

vue.js

nuxt.js

I use Nuxt.js and I have dynamic page /items/{id}:

<template>
  <div>
    <h1>Item #{{ item.id }} &laquo;{{ item.title }}&raquo;</h1>
  </div>
</template>

<script>
import { api } from '../../mo/api'

export default {
  asyncData({ params }) {
    return api(`items/${params.id}`)
  },
}
</script>

Backend API returns object {item: {id: .., title: "...", ...}}. But if an item with specified ID not exist API returns 404 response. And Vue crash with "[Vue warn]: Property or method "item" is not defined on the instance but referenced during render."

How can I handle 404 response?

My api.js module:

import axios from 'axios'

export function api(url) {
  url = encodeURIComponent(url)
  return axios
    .get(`http://localhost:4444/?url=${url}`)
    .then(({ data }) => {
      return data
    })
    .catch((err) => {
      // 404 catch there
    })
}

Solution:

Need to read manual: https://nuxtjs.org/guide/async-data/#handling-errors

like image 214
vasa_c Avatar asked Nov 27 '18 12:11

vasa_c


2 Answers

just execute error function :)

<script>
export default {
  asyncData({ params, error }) {
    return axios
      .get(`https://my-api/posts/${params.id}`)
      .then((res) => {
        return { title: res.data.title }
      })
      .catch((e) => {
        error({ statusCode: 404, message: 'Post not found' })
      })
  },
}
</script>
like image 128
Jakub Gadawski Avatar answered Oct 24 '22 18:10

Jakub Gadawski


If you're using the fetch() hook, this is how it should be written

<script>
export default {
  async fetch() {
    try {
      await fetch('https://non-existent-website.commmm')
        .then((response) => response.json())
    } catch (error) {
      this.$nuxt.context.error({
        status: 500,
        message: 'Something bad happened',
      })
    }
  },
}
</script>

More context available here: https://nuxtjs.org/announcements/understanding-how-fetch-works-in-nuxt-2-12/#error-handling

like image 2
kissu Avatar answered Oct 24 '22 18:10

kissu