web-dev-qa-db-ja.com

next.jsルートで末尾のスラッシュをどのように処理できますか?

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ルーターを拡張する方法はありますか?

5
futuraprime

更新:next exportを使用している場合は、next.config.jsexportTrailingSlashを追加することで問題を解決できます

この記事の執筆時点では、独自のカスタムサーバーを定義せずにこの問題を解決する方法はないようです。

以前の答え:

以下に示す新しいファイルblog.jsを作成する必要があります。

enter image description here

次の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は使用されていません。

1
eenagy

これを_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,
  };
};
  • App.getInitialPropsは最初のサーバー側で呼び出されます
  • URLがスラッシュで終わっているかどうかを知りたいだけなので、パスとクエリパラメータを分割します。
  • URLがスラッシュで終わるかどうか尋ねます
  • URLの最後のスラッシュを何も置き換えません
  • スラッシュなしのURLにリダイレクトします+クエリパラメータがある場合は
0

これに対する解決策はありません。これはまだ大きな問題です。しかし、私は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を手動で指定することを要求します-しかし少なくともそれは何かです。

0
Ev Haus