我使用 Nuxt.js 并且我有动态页面“/items/{id}”:
<template>
<div>
<h1>Item #{{ item.id }} «{{ item.title }}»</h1>
</div>
</template>
<script>
import {api} from "../../mo/api";
export default {
asyncData({params}) {
return api(`items/${params.id}`);
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
后端 API 返回对象 {item: {id: .., title: "...", ...}}。但是如果指定 ID 的项目不存在 API 返回 404 响应。并且 Vue 崩溃并显示“[Vue warn]:属性或方法“item”未在实例上定义,但在渲染期间被引用。”
如何处理 404 响应?
我的“api.js”模块:
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
});
}
Run Code Online (Sandbox Code Playgroud)
解决方案:
需要阅读手册:https : //nuxtjs.org/guide/async-data/#handling-errors :)
只需执行错误函数:)
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' })
})
}
}
Run Code Online (Sandbox Code Playgroud)