我正在 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/