NextJS页面名称与URL名称不同

时间:2020-08-31 06:41:48

标签: javascript node.js reactjs next.js

我正在用NextJS做一个项目,但是我发现页面文件夹中的文件名指示了URL栏中显示的路径。

有什么办法可以使我拥有这样的结构?


 - Pages
   - 1.jsx
   - 2.jsx
   - 3.jsx

然后将其呈现为url或路径:http://localhost:3000/about 3.jsx将被映射到about链接吗?

2 个答案:

答案 0 :(得分:0)

在next.js中创建自定义服务器

关注this官方文档。您可以在代码中管理每条路线。

// 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 === '/about') {
      app.render(req, res, '/3', query) // Pass the file name here so that it reads the proper file from /pages directory
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

其他示例在这里:-

答案 1 :(得分:-1)

在Next.js中,页面是从页面目录中的文件导出的React组件。 页面根据文件名与路由关联。

例如,正在开发中:

pages/index.js/路由相关。

pages/posts/first-post.js/posts/first-post路由相关。

这是使用Next.js创建多个页面的方法。只需在pages目录下创建一个JS文件,该文件的路径即成为URL路径。您可以随意命名,只要保持应用程序的一致性就可以了。

此外,由于听起来您正在尝试控制页面标题/元数据在浏览器中的显示方式,因此请务必查看这篇文章,其中确切说明了如何执行此操作。

How to create custom page heads/metadata

有关更多详细信息,可以使用以下链接查看其他Next.js文档。

Next.js basic page documentation

A more complex article about dynamic routes

相关问题