Nuxtfetch方法,若API错误使整个站点响应404错误



当API上出现404错误时,如何使nuxt站点响应404。

调用是在客户端上进行的,因此使用了fetch方法:

这里有一个演示:codesandbox演示

代码片段

索引.vue

<template>
<section>
<h1>Testing custom error</h1>
<p v-if="$fetchState.pending">Fetching mountains...</p>
<PageError v-else-if="$fetchState.error" />
<p v-else>Fetch success</p>
</section>
</template>
<script>
import PageError from '~/components/PageError.vue'
export default {
components : {
PageError
},
async fetch() {
await this.$axios.$get("https://api.nuxtjs.dev/mountain");
},
fetchOnServer: false,
};
</script>

PageError.vue

<!--Make this component respond with 404 -->
<template>
<section>
<h1>404 item not found</h1>
<p>How to I make site respond with 404</p>
</section>
</template>

为什么这是一个问题

  • 爬网程序不会注意到页面没有内容,最终会对404页进行索引。。。因为我希望谷歌不要用404抓取网站…直到发布修复程序,我可以从search console验证修复程序

与其仅仅用文本来回应发生了错误并且找不到页面。。。。我希望site的状态为404。

注意:当错误组件被触发时,我可以添加一个<meta name="robots" content="noindex,follow"/>。。。只是问NUXT是否有可能获得404。

我必须研究细节本身,但到目前为止,我认为您需要捕捉axios的错误,有点像:

...      
.then(response => {
return response
})
.catch(error => {
return error
// return Promise.reject(error)
})
...

然后你可以v-if=";。。。错误";以使该组件出现。

我希望这能把你推向更好的方向。

最新更新