如何从 Next Js URL 中删除子文件夹名称?

Rya*_*gel 6 reactjs next.js

我在页面/用户/文件夹中创建了一堆文件。我可以通过以下 URL 访问它们:

http://localhost:3000/user/signup
http://localhost:3000/user/signin
http://localhost:3000/user/profile
Run Code Online (Sandbox Code Playgroud)

我想做的是删除用户/部分,以便 URL 如下所示:

http://localhost:3000/signup
http://localhost:3000/signin
http://localhost:3000/profile
Run Code Online (Sandbox Code Playgroud)

稍后我将在页面内添加更多文件夹以用于帖子等。实现此目的的最佳方法是什么?

And*_*rei 1

为此,您需要使用自定义的server.js. 请参阅文档的自定义服务器和路由部分。

你的代码看起来像这样:

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

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

app.prepare().then(() => {
  createServer((req, res) => {
    // Be sure to pass `true` as the second argument to `url.parse`.
    // This tells it to parse the query portion of the URL.
    const parsedUrl = parse(req.url, true)
    const { pathname, query } = parsedUrl

    if (pathname === '/signup') {
      app.render(req, res, '/user/signup', query)
    } else if (pathname === '/signin') {
      app.render(req, res, '/user/signin', query)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(3000, err => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})
Run Code Online (Sandbox Code Playgroud)

另一种选择是将文件本身移动到./pages文件夹内,但我怀疑您想避免这样做(因此是您的问题)。