Hi,
for some reasons I have to handle my vue-router aliases and some times return a 404 if some given conditions are not respected.
I see I can easily set res status to 404 like below:
module.exports = function (req, res, next) {
// check incoming request and do some logic
// ......................
// then check if the condition is true and eventually redirect to 404
if (aliasesLookup[req.path] && aliasesLookup[req.path] !== country) {
res.status(404).send('Not found')
return
}
next()
}
However, I would like also to set the nuxt.js 404 template, is there any way to achieve that? At the moment I just get a white page with the 404 error in console.
Use error page and error.statusCode to customize 404 error page.
// layouts/error.vue
<template>
<div class="container">
<h1 v-if="error.statusCode === 404">Page not found</h1>
<h1 v-else>An error occurred</h1>
<nuxt-link to="/">Home page</nuxt-link>
</div>
</template>
<script>
export default {
props: ['error']
}
</script>
Thanks @clarkdo, unfortunately it doesn't seem to work like that.
I am using a server middleware in nuxt.config.js
// nuxt.config.js
serverMiddleware: [
'~/routes/alias-handler'
]
// aliasHanlder.js
module.exports = function (req, res, next) {
// check incoming request and do some logic
// ......................
// then check if the condition is true and eventually redirect to 404
if (aliasesLookup[req.path] && aliasesLookup[req.path] !== country) {
res.status(404).send('Not found')
return
}
next()
}
I correctly get the 404 on the Front End but I can't seem to get any template associated to it, not even the standard nuxt.js error template.
Try below together with layout/error.vue
module.exports = function (req, res, next) {
// check incoming request and do some logic
// ......................
// then check if the condition is true and eventually redirect to 404
if (aliasesLookup[req.path] && aliasesLookup[req.path] !== country) {
next({ statusCode: 404, message: 'not found'})
} else {
next()
}
}
Sorry for the late reply, still not working, I will investigate and I'll update this thread if I find any solution, thanks for your help
Pls check: https://github.com/clarkdo/nuxt-issues/tree/issue_2204
Visit: http://localhost:3000/test404
Have we considered using validate() within the pages?
export default { validate ({ params }) { // Must be a number return /^\d+$/.test(params.id) } }If the validate method does not return
true, Nuxt.js will automatically load the 404 error page.
Hi @sparecycles , yes indeed, this is quite an old discussion, after the validate method release, I used it to solve my problem
Great to hear it. I was having a similar issue and just thought I'd drop a note here in case anyone else was stuck.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.