javascript - Next.js 在 getInitialProps 中返回 404 错误页面

标签 javascript node.js serverside-javascript next.js

目前我正在关注这个关于如何在 getInitialProps 中重定向用户的例子

https://github.com/zeit/next.js/wiki/Redirecting-in-%60getInitialProps%60

问题是,如果我想像这样返回 404,它将返回一个空白页面,而不是通常的 Next.js 404 错误页面。

context.res.writeHead(404)
context.res.end();

请注意,我知道使用 ExpressJs 和使用状态码 404 是可行的,但是,对于这个项目,我不允许使用 ExpressJs,所以我需要使用典型的 nodejs writeHead 来完成它。

最佳答案

下一个 v10 允许返回 404 页面(不带 Prop ,但如下所示)

  if (!checkItem) {
    return {
      notFound: true
    }
  }

适合我的完整代码:✅✅✅

export const getServerSideProps = wrapper.getServerSideProps(async ({ req, res, locale, query, store }) => {
  const { productId, categoryId } = query
   
  const checkItem = await getProductBySlugSSR(productId, categoryId, store)

  if (!checkItem) {
    return { // <-----------------does the trick here!!
      notFound: true
    }
  }
    
  return {
    props: {
      ...await serverSideTranslations(locale, ['common']),
    }
  }
})

文档:https://nextjs.org/blog/next-10#notfound-support

关于javascript - Next.js 在 getInitialProps 中返回 404 错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47586505/

相关文章:

php - 从 PHP 调用 Javascript 函数

javascript - php session 随机丢失,无法理解为什么

javascript - 如何使用父/子在javascript中选择正确的div

javascript - 无法从特定选择中获取选项

Javascript Node.js Unicode 正则表达式

javascript - 为什么服务器端 Javascript 没有被广泛使用?

Chrome 上的 Javascript TypeError 事件异常

javascript - 如何显示使用 javascript 检查的单选按钮的文本框 onclick?

node.js - Gulp:如何从流数组的 promise 创建流?

javascript - Nodejs mysql模块未连接到数据库