Nuxt.js并处理动态页面的API 404响应

时间:2018-11-27 12:50:15

标签: vue.js nuxt.js

我使用Nuxt.js,并且具有动态页面“ / items / {id}”:

Option Explicit

Sub test()

    Dim LR As Long
    Dim GroupName As String
    Dim LC As Long
    Dim i As Long
    Dim j As Long
    Dim LC2 As Long
    Dim LR2 As Long
    Dim Exist As Boolean

    LC = Sheet2.Cells(1, Sheet2.Columns.Count).End(xlToLeft).Column
    LR = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row

    For i = 2 To LR
        Exist = True
        GroupName = Sheet1.Cells(i, 1).Value

        If LC = 1 And Sheet2.Cells(1, 1).Value = "" Then
            Sheet2.Cells(1, 1).Value = GroupName
            Sheet2.Cells(1, 1).Offset(2, 0).Value = Sheet1.Cells(i, 2).Value
        Else
            LC2 = Sheet2.Cells(1, Sheet2.Columns.Count).End(xlToLeft).Column
            For j = 1 To LC2
                If GroupName = Sheet2.Cells(1, j).Value Then
                    LR2 = Sheet2.Cells(Rows.Count, j).End(xlUp).Row
                    Sheet2.Cells(LR2 + 1, j).Value = Sheet1.Cells(i, 2).Value
                    Exist = True
                    Exit For
                Else
                   Exist = False
                End If
            Next j
            If Exist = False Then
                Sheet2.Cells(1, LC2 + 1).Value = GroupName
                Sheet2.Cells(1, LC2 + 1).Offset(2, 0).Value = Sheet1.Cells(i, 2).Value
            End If
        End If

    Next i

End Sub

后端API返回对象{item:{id:..,title:“ ...”,...}}。 但是,如果不存在具有指定ID的项目,则API会返回404响应。 Vue崩溃并显示“ [Vue warn]:属性或方法“ item”未在实例上定义,而是在渲染期间引用。”

如何处理404响应?

我的“ api.js”模块:

<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>

解决方案:

需要阅读手册:https://nuxtjs.org/guide/async-data/#handling-errors:)

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

仅执行错误功能:)

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' })
        })
      }
    }