Ara*_*oca 6 javascript node.js express reactjs next.js
使用next@9.1.7与快递的自定义服务器。如何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)
})
Run Code Online (Sandbox Code Playgroud)
我终于解决了:
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)
})
Run Code Online (Sandbox Code Playgroud)
如果有人知道更优雅的解决方案,将受到欢迎。