我正在尝试使用 Nuxt.js 创建一个 SSG 网站。 当我访问 nuxt.config.js 的生成属性中未设置的路由时, 我想在不改变URL的情况下显示404页面的内容。(使用htaccess)
以下是正在 build 中的站点
http://we-are-sober.d3v-svr.com/xxxx
这按预期工作。
http://we-are-sober.d3v-svr.com/user/xxxx
这没有按预期工作。
暂时显示404页面的内容,但很快就执行了基于“user/_id.vue”动态路由的流程。
问题的关键在于,不存在的路由表现得就像它存在一样。 有谁知道如何解决这个问题吗?
这是源代码。 https://github.com/yhirochick/rewrite_test
404.vue
https://github.com/yhirochick/rewrite_test/blob/master/pages/404.vue
user/_id.vue
https://github.com/yhirochick/rewrite_test/blob/master/pages/user/_id.vue
nuxt.config.js
https://github.com/yhirochick/rewrite_test/blob/master/nuxt.config.js#L43-L45
.htaccess
https://github.com/yhirochick/rewrite_test/blob/master/static/.htaccess
我是日本人。以上文字基于谷歌翻译。 可能有点难以理解,但是谢谢。
最佳答案
我在尽量减少所需 API 调用的同时处理此类问题的方法如下:
- 生成一个全新的 Nuxt 项目
- 安装axios:
yarn add -D axios
- 将其添加到
nuxt.config.js
文件
import axios from 'axios'
export default {
...
generate: {
routes: async () => {
const users = await axios.get('https://jsonplaceholder.typicode.com/users')
return users.data.map((user) => ({
route: `/users/${user.id}`,
payload: user,
}))
},
fallback: 'no-user.html', // this one is not needed anymore if you ditch the redirect!
},
}
这将生成所有需要的路由,同时通过稍后传递到页面的有效负载
将调用保持在最低限度。更多信息可参见the docs .
- 然后,创建
/pages/users/_id.vue
页面就可以了
<template>
<div>
<div v-if="user">User name: {{ user.name }}</div>
<div v-else-if="error">{{ error }}</div>
</div>
</template>
<script>
export default {
asyncData({ payload }) {
if (payload && Object.entries(payload).length) return { user: payload }
else return { error: 'This user does not exist' } // this will also catch users going to `/users/`
},
}
</script>
- 创建一些
no-user.vue
页面,error.vue
布局,你应该是gucci
最后,我们从模拟的 API 中获得了 10 个用户。所以这些是以下情况:
- 如果我们转到
/users/5
,用户已经是静态的,因此我们无需任何额外的 API 调用即可获得其信息 - 如果我们转到
/users/11
,则用户在构建时不存在,因此他不在这里,我们将显示错误 - 如果我们转到
/users
,我们仍然会被发送到/pages/users/_id
页面,但由于:id
> 在那里是可选的,它会出错并仍然显示错误,index.vue
当然可以处理这种情况
我的 github 存储库可以在这里找到:https://github.com/kissu/so-nuxt-generate-placeholder-users
这种方法在 Nuxt 中称为完全静态
,如下所述:https://nuxtjs.org/announcements/going-full-static/
关于apache - 如何在 Nuxt 路由器中手动生成带有 .htaccess 404 页面回退的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68417337/