javascript - NextJS 页面名称与 url 名称不同

标签 javascript node.js reactjs next.js

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

有什么方法可以让我拥有这样的结构:


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

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

最佳答案

在 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')
  })
})

其他例子在这里:-

关于javascript - NextJS 页面名称与 url 名称不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63665973/

相关文章:

reactjs - 在 DatePicker for AntD 中隐藏日历图标(后缀图标)的正确方法

javascript - jscript/jquery : fade in divs 1 by 1, 中间有暂停

javascript - 正则表达式:禁用符号

javascript - 在模块之间共享 promise 与拥有多个 promise

javascript - 使用 ListView 自动完成 TextInput - 必须点击 ListView 两次才能选择列表项

javascript - 想要生成唯一的数字 id,不能使用 node-uuid 因为后端需要数字 id

javascript - 为什么我需要执行 $(document.body) 以使用 Mootools Element 方法扩展 document.body?

javascript - 当页面加载到 div 类时,如何通过 javascript 追加一个类?

eclipse - 如何将nodejs项目导入mac中的nodejs eclipse

node.js - 网络服务器之上的http服务器