Next.jsアプリを設定しようとしていますが、末尾にスラッシュがあるルートを処理できません。したがって、たとえば、次のようなページ構造があるとします。
pages
- index.js
- blog
- index.js
- [slug].js
次に、/
に行くとベースindex.js
が得られ、/blog
に行くとblog/index.js
が得られ、/blog/my-post
に行くとblog/[slug].js
が得られます。
しかし、/blog/
にアクセスすると404エラーが発生し、next.jsルーターを完全に置き換えずにこれを処理する方法はないようです。/blog/
を/blog
にリダイレクトすることもできません。これを回避する方法はありますか、またはカスタムルーターが必要ですか?完全に置き換えることなく、これらを処理できるようにnext.jsルーターを拡張する方法はありますか?
更新:next export
を使用している場合は、next.config.js
にexportTrailingSlash
を追加することで問題を解決できます
この記事の執筆時点では、独自のカスタムサーバーを定義せずにこの問題を解決する方法はないようです。
以前の答え:
以下に示す新しいファイルblog.js
を作成する必要があります。
次のserver.js
const express = require('express')
const next = require('next')
const PORT = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app
.prepare()
.then(() => {
const server = express()
server.get('/blog', (req, res) => {
const actualPage = '/blog'
// const queryParams = { title: req.params.id }
app.render(req, res, '/blog', {})
})
server.get('/blog/:id', (req, res) => {
const actualPage = '/blog/[id]'
const queryParams = { title: req.params.id }
app.render(req, res, actualPage, queryParams)
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(PORT, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})
})
.catch(ex => {
console.error(ex.stack)
process.exit(1)
})
node server.js
がサーバーを起動し、必要なマッピングが得られます。
この例ではblog/index.js
は使用されていません。
これを_app.jsファイルに追加できます
MyApp.getInitialProps = async ctx => {
const pathAndQueryDivided = ctx.ctx.req.url.split('?');
if (pathAndQueryDivided[0].endsWith('/')) {
const urlWithoutEndingSlash = pathAndQueryDivided[0].replace(/\/*$/gim, '');
ctx.ctx.res.writeHead(301, {
Location: urlWithoutEndingSlash + (pathAndQueryDivided.length > 1 ? `?${pathAndQueryDivided[1]}` : ''),
});
ctx.ctx.res.end();
return {};
}
const initialProps = await App.getInitialProps(ctx);
return {
...initialProps,
};
};
これに対する解決策はありません。これはまだ大きな問題です。しかし、私はNext.js 9.x.xでこの問題を回避するために使用している非常に恐ろしいハックをしています。
私の/pages/_error.js
次のコードを追加しました:
FourOhFour.getInitialProps = ({asPath, res}: any): any => {
const supportedPaths = [
'/page1/',
'/page2/',
'/page3/'
];
for (let i = 0, l = supportedPaths.length; i < l; i++) {
const path = supportedPaths[i];
if (asPath === path) {
res.writeHead(301, {Location: path.substring(0, path.length - 1)});
return res.end();
}
}
return {};
};
これにより、指定されたすべてのページが正しいパスにリダイレクトされます。
これはあなたのために機能しないかもしれないあなたのすべてのページURLを手動で指定することを要求します-しかし少なくともそれは何かです。