NextJS:如何在根处理多个动态路由

csb*_*nes 12 express next.js

目标:我想实现的GitHub风格路由,其中abcdgithub.com/abcd能够解决用户的个人资料页或一个团队页面。

我目前有一个这样的版本(见下文)。不幸的是,我在 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}`);
  });
});
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*son 23

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
}
Run Code Online (Sandbox Code Playgroud)

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])
Run Code Online (Sandbox Code Playgroud)

多段

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

pages/[username].js      -> (matches http://yourwebsite.com/[username])
pages/[username]/[repo]  -> (matches http://yourwebsite.com/[username]/[repo])
Run Code Online (Sandbox Code Playgroud)

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

路由“前缀”

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

多条动态路由

不同段的动态数量

您还可以拥有包含任意数量动态段的动态路由。为此,您需要在动态路由文件名中使用省略号(“...”):

/pages/[...userDetails].js  -> (will match http://website.com/[username]/[repo]/[etc]/[etc]/[forever]) 
Run Code Online (Sandbox Code Playgroud)

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

  • 啊,那么你需要在页面代码中处理它。即抓取字符串,确定它是团队还是用户,然后导入正确的组件以显示正确的页面。 (3认同)
  • 真正的答案是:这是一个设计糟糕的路由方案,并且随着站点的扩展,将动态路由作为根会引发各种令人头痛的问题。为动态路由制定正确的前缀路由 - 在本例中,“/pages/users/[username].js”和“/pages/teams/[team].js”将使事情变得更加简单。我非常怀疑用户路由是否需要像这样位于根级别。 (3认同)
  • 是的,问题是我想要两个动态路由,“/pages/[username].js”和“/pages/[team].js”,这不起作用(可以理解)。 (2认同)