JavaScript - Express JS - 动态面包屑创建(名称 + URL)

JavaScript - Express JS - Dynamic Breadcrumbs Creation (Name + URL)

我想创建一些中间件(服务器端),它会自动生成面包屑并将其传递给客户端。我正在为模板引擎使用 handlebars,并为我的路由使用 express。

假设我有这样一条路线:

/* GET home page. */
router.get('/services/heroku/standards', getBreadcrumbs, (req, res) => {
  res.render('index', {
    breadcrumbs: req.breadcrumbs,
  });
});

我想要一个中间件函数,它通过并获取 req.originalUrl,然后创建一个 JSON 对象/面包屑数组。

到目前为止我已经创建了这个函数:

// Function for getting breadcrumbs of the page
function getBreadcrumbs(req, res, next) {
  // Initizating the JSON Object.
  const myJson = {};
  // Getting the URL and splitting the variables into an Array.
  const pathArray = req.originalUrl.split('/');
  // Removing the first value in the array as it will be empty.
  pathArray.shift();
  // Getting the length of the array.
  const arrayLength = pathArray.length;
  // Looping through the array and pushing value to the Json Object
  for (let i = 0; i < arrayLength; i++) {
    // Adding the breadcrumb name E.G home
    myJson.breadcrumbName = pathArray[i];
    // Adding the breadcrumb URL E.G /home/heroku/standards - **TROUBLE HERE!!!!!**
    myJson.breadcrumbUrl = req.originalUrl;
  }
  // Storing the array above in the request.
  req.breadcrumbs = pathArray;
  // If the request is the home page we need to change the value to: Home
  if (req.breadcrumbs[0] === '') {
    // Change the value of the first array to Home
    req.breadcrumbs[0] = 'Home';
  }
  // Finished the middleware request.
  next();
}

如果 URL 是:/services/heroku/standards.

,我希望得到这种预期结果
const myJson = [
{
    breadcrumbName: "Services",
    breadcrumbUrl: "/services"
},
{
    breadcrumbName: "Heroku",
    breadcrumbUrl: "/services/heroku"
},
{
    breadcrumbName: "Standards",
    breadcrumbUrl: "/services/heroku/standards"
}

如果有更有效的方法来获得此结果,请告诉我。

找到答案了。这会将面包屑存储到 req.breadcrumbs

// Function for getting breadcrumbs of the page
    function getBreadcrumbs(req, res, next) {
      const urls = req.originalUrl.split('/');
      urls.shift();
      req.breadcrumbs = urls.map((url, i) => {
        return {
          breadcrumbName: (url === '' ? 'Home' : url.charAt(0).toUpperCase() + url.slice(1)),
          breadcrumbUrl: `/${urls.slice(0, i + 1).join('/')}`,
        };
      });
      next();
    }