簡體   English   中英

如何使用 Next.js 檢查自定義服務器中是否存在頁面

[英]How to check if a page exist in a custom server using Next.js

next@9.1.7與帶有 express 的自定義服務器一起使用。 如何在我的server.js知道在handle(req, res)調用之前 next.js 頁面是否存在?

我嘗試使用app.router.execute但它總是返回 false。 所以我想那不是辦法。 我檢查了 Next.js 文檔,但沒有得到任何解決方案......有人有想法嗎?

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const server = express()
const handle = app.getRequestHandler()

// ...

server.get('*', async (req, res) => {
  const { url, fixed } = fixUrl(req)

  // pageExists is always false 🤨...
  const pageExists = await app.router.execute(req, res, req.url) 

  // Fix the url and redirect only if the page exists 
  // (to avoid redirects to 404 pages)
  if (fixed && pageExists) {
    res.redirect(301, url)
    return
  }

  handle(req, res)
})

我終於解決了:

const glob = require('glob')
const path = require('path')

// ...
const pagesDir = path.resolve(`${__dirname}/../src/pages`)
const pages = glob.sync(`${pagesDir}/**/*.js`)
  .map(p => p
    .replace(pagesDir, '')
    .replace('index.js', '')
    .replace('.js', '')
  )

// ...

server.get('*',(req, res) => {
  const { url, fixed } = fixUrl(req)

  if (fixed && pages.includes(url.split('?')[0])) {
    res.redirect(301, url)
    return
  }

  handle(req, res)
})

如果有人知道更優雅的解決方案,它將受到歡迎。

這個可怕的 hack 並沒有嚴格地告訴你在調用handle之前是否存在路由,但它確實讓你在下一次向res呈現任何內容之前掛鈎並應用你自己的 404 錯誤自定義處理。

const errorRenderer = app.server.renderErrorToHTML;
app.server.renderErrorToHTML = function(err, req, res, pathname, query) {
    if (res.statusCode == 404) {
        // handle the 404 however you like
        return null;
    } else {
        return errorRenderer.apply(this, arguments);
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM