英文:
How to set a response status for a nuxt page? 404
问题
我想在我的/not-found页面上设置响应状态为404。
我尝试过:
- 在~/error.vue中创建自定义错误页面,并使用
createError
抛出致命错误,但它只发送200。 - 抛出致命错误并使用NuxtErrorBoundary。但它什么都不做。
- 在setup中使用setResponseStatus:
const event = useRequestEvent()
setResponseStatus(event, 404)
setResponseStatus(event, 404, 'Page Not Found')
但必须在服务器上执行(正如他们所说),所以它不总是在setup上起作用。
- 在
~/server/middleware
中使用中间件:
// setResponseStatus在所有~/server/*中未定义
// 所以我不得不从这里导入它
import { setResponseStatus } from '../../node_modules/nuxt/dist/app';
export default defineEventHandler((event) => {
setResponseStatus(event, 404)
})
这要么什么都不做,要么只会引发nuxt实例不可用
错误。
这不应该那么复杂,对吗?或者我在这里漏掉了什么?
目前正在考虑在nginx
中处理404。
英文:
I want to set response status 404 on my /not-found page.
I tried to:
- create custom error page in ~/error.vue and throw fatal errors with
createError
. But it just sends 200 - throw fatal errors and use NuxtErrorBoundary. But it doesn't do anything
- use setResponseStatus in setup
const event = useRequestEvent()
setResponseStatus(event, 404)
setResponseStatus(event, 404, 'Page Not Found')
But it must be executed (as they say) on the server, so it doesn't always work on setup.
- Use middleware in
~/server/middleware
):
// setResponseStatus wasn't defined in all ~/server/*
// so I had to import it from here
import { setResponseStatus } from '../../node_modules/nuxt/dist/app'
export default defineEventHandler((event) => {
setResponseStatus(event, 404)
})
Which either does nothing or just causes nuxt instance unavailble
error.
It shouldn't so complicated, right? Or what am I missing here?
Currently considering handling 404 in nginx
instead.
答案1
得分: 1
使用设置函数
<script setup>
if (process.server) {
const event = useRequestEvent()
setResponseStatus(event, 404)
}
</script>
因为它只在服务器上运行,所以可以将其包装在 process.server
中。
使用(内联)路由中间件
<script setup>
definePageMeta({
middleware: [
() => {
const event = useRequestEvent()
setResponseStatus(event, 404)
}
],
});
</script>
请注意,您需要一个路由中间件,而不是服务器中间件。服务器中间件会在每个请求上运行,这可能不是您想要的。
出于简单起见,我将中间件内联在此处,但您也可以将其放在中间件目录中。
英文:
Using a setup function
<script setup>
if (process.server) {
const event = useRequestEvent()
setResponseStatus(event, 404)
}
</script>
Since it only works on server you can wrap it in process.server
.
Using (inline) route middleware
<script setup>
definePageMeta({
middleware: [
() => {
const event = useRequestEvent()
setResponseStatus(event, 404)
}
],
});
</script>
Note that you need a route middleware, not a server middleware. Server middleware run on every request which is probably not what you want.
For the sake of simplicity I made the middleware inline but you can have it in the middleware directory.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论