gpt4 book ai didi

express - 下一个JS : How to handle multiple dynamic routes at the root

转载 作者:行者123 更新时间:2023-12-03 15:01:23 27 4
gpt4 key购买 nike

Goal: I would like to achieve github style routing, where abcd in github.com/abcd could resolve to a user profile page or a team page.



我目前有一个这样的版本(见下文)。不幸的是,我在 2 个动态路由之间导航时偶尔会出现白页闪烁。

我的服务器文件看起来像:

const express = require('express');
const next = require('next');
const { parse } = require('url');
const resolveRoute = require('./resolveRoute');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({
dev,
});
const nextHandle = nextApp.getRequestHandler();

const STATIC_ROUTES = [
'/about',
'/news',
'/static',
];

const DYNAMIC_ROUTE_MAP = {
user: '/[user]',
team: '/teams/[team]',
};

nextApp.prepare().then(() => {
const server = express();

server.get('*', async (req, res) => {
// pass through next routes
if (req.url.indexOf('/_next') === 0) {
return nextHandle(req, res);
}

// pass through static routes
if (
req.url === '/' ||
STATIC_ROUTES.map(route => req.url.indexOf(route) === 0).reduce(
(prev, curr) => prev || curr,
)
) {
return nextHandle(req, res);
}

// try to resolve the route
// if successful resolves to an object:
// { type: 'user' | 'team' }
const resolvedRoute = await resolveRoute(req.url);
if (!resolvedRoute || !resolvedRoute.type) {
console.error('🛑 Unable to resolve route...');
return nextHandle(req, res);
}

// set query
const { pathname } = parse(req.url);
const paths = pathname.split('/').filter(path => path.length > 0);
const query = {
[resolvedRoute.type]: paths.length > 0 ? paths[0] : null,
};

// render route
return nextApp.render(
req,
res,
DYNAMIC_ROUTE_MAP[resolvedRoute.type],
query,
);
});

server.listen(port, err => {
if (err) throw err;
console.log(`🌎 Ready on http://localhost:${port}`);
});
});

我想知道是否有更好的方法来处理这个问题,或者我是否需要远离 NextJS。

最佳答案

Next.JS 内置了动态路由,不需要您创建自定义 server.js 文件。如果你想与 Next.JS 完全兼容,你应该改用它的动态路由。

要在 Next.JS 中创建动态路由,您可以创建名称用方括号括起来的页面,例如/pages/[username].js .这将匹配您的基本域上的所有路由,因此您可以使用 github 设置您提到的示例,例如http://yourwebsite.com/csbarneshttp://yourwebsite.com/anotherusername .

在上面的示例中,您可以从 getInitialProps 中的查询参数中获取 Next.JS 页面中的用户名。就像使用任何查询字符串参数一样:

static getInitialProps({query}) {
console.log(query.username); // the param name is the part in [] in your filename
return {query}; // you can now access this as this.props.query in your page
}

Next.JS 总是在动态路由之前匹配静态路由,这意味着您的 /pages/目录可以是这样的:
pages/index.js       -> (will match http://yourwebsite.com)
pages/about.js -> (will match http://yourwebsite.com/about)
pages/contact.js -> (will match http://yourwebsite.com/contact)
pages/[username].js -> (will match http://yourwebsite.com/[anything_else])

多段

您可以有多个分段动态路由,例如 http://website.com/[username]/[repo]在您的 pages 中使用文件夹目录:
pages/[username].js      -> (matches http://yourwebsite.com/[username])
pages/[username]/[repo] -> (matches http://yourwebsite.com/[username]/[repo])

在这种情况下,您的查询对象将包含 2 个参数: { username: ..., repo: ...} .

路由“前缀”

如果您愿意,您可以通过在 pages 中创建文件夹来拥有多个具有不同“前缀”的动态路由。目录。这是一个带有 website.com/[username] 的示例文件夹结构路线和 website.com/teams/[team]路线:

multiple dynamic routes

不同段的动态数量

您还可以拥有包含任意数量动态段的动态路由。为此,您需要在动态路由文件名中使用省略号(“...”):
/pages/[...userDetails].js  -> (will match http://website.com/[username]/[repo]/[etc]/[etc]/[forever]) 

在这种情况下,您的 this.props.userDetails变量将返回一个数组而不是一个字符串。

关于express - 下一个JS : How to handle multiple dynamic routes at the root,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59790906/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com