我想创建一些中间件(服务器端),将自动生成面包屑,并通过客户端。我使用把手作为模板引擎,使用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();
}如果网址是:/services/heroku/standards.,我希望会出现这样的预期结果
const myJson = [
{
breadcrumbName: "Services",
breadcrumbUrl: "/services"
},
{
breadcrumbName: "Heroku",
breadcrumbUrl: "/services/heroku"
},
{
breadcrumbName: "Standards",
breadcrumbUrl: "/services/heroku/standards"
}如果有更有效的方法来获得这个结果,请告诉我。
发布于 2017-02-03 00:22:42
找到答案了。这将把面包屑存储到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();
}https://stackoverflow.com/questions/42001095
复制相似问题