如何处理 next.js 路由中的斜杠? [英] How can you handle trailing slashes in next.js routes?

查看:32
本文介绍了如何处理 next.js 路由中的斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置 next.js 应用程序,但在处理带有斜杠的路线时遇到了问题.因此,例如,如果我有这样的页面结构:

I am trying to set up a next.js app, but I'm having trouble handling routes with a trailing slash. So, for example, if I have a pages structure like this:

pages
 - index.js
 - blog
   - index.js
   - [slug].js

然后去 / 给我基本的 index.js,去 /blog 给我 blog/index.js,然后转到 /blog/my-post 给我 blog/[slug].js — 到目前为止一切顺利.

then going to / gives me the base index.js, going to /blog gives me blog/index.js, and going to /blog/my-post gives me blog/[slug].js — so far so good.

但是转到 /blog/ 会给我一个 404 错误,如果不完全替换 next.js 路由器,似乎根本无法处理这个问题——我什至无法重定向 <代码>/blog/ 到 /blog.有什么办法可以解决这个问题,还是我需要一个自定义路由器?有没有办法扩展 next.js 路由器,让我处理这些,而不用完全替换它?

But going to /blog/ gives me a 404 error, and there appears to be no way at all to handle this without entirely replacing the next.js router—I can't even redirect /blog/ to /blog. Is there any way around this, or do I need a custom router? Is there a way to extend the next.js router in a way that will let me handle these, without entirely replacing it?

推荐答案

更新:如果您使用 next export,则可以通过将 exportTrailingSlash 添加到您的next.config.js

UPDATE: If you are using next export than you can solve the issue by adding exportTrailingSlash to your next.config.js

在撰写本文时,如果不定义您自己的自定义服务器,似乎无法解决此问题.

As of this writing, there seems to be no way to solve this issue without defining your own custom server.

上一个答案:

您必须创建一个新文件 blog.js,如下所示:

You must create a new file blog.js shown bellow:

使用以下 server.js

With the following 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 应该启动你的服务器并且你会得到你需要的映射.

node server.js should start your server and you would have the mapping that you need.

注意,blog/index.js 在这个例子中没有用到.

Note, blog/index.js is not used in this example.

这篇关于如何处理 next.js 路由中的斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆