(Node/Express) Express-sitemap 生成不正确的站点地图

(Node/Express) Express-sitemap generating incorrect sitemap

我正在尝试使用 express-sitemap 中间件为我的网站生成站点地图。我的代码如下:

var sitemap = require('express-sitemap')();
//...
app.get('/', function(req, res) {
  res.render('index')
})
//...
posts = [
  post2 = {
    "url":
    "wild-birds",
  },    
  post1 = {
    "url":
    "top-dogs-cats",
  }
]

app.get('/:leg', function(req, res, next) {
    for (i=0; i<posts.length; i++) {
        if (req.params.leg == posts[i].url) {
            res.render('post', { posts2:posts[i] });
        }
    }
//The above code checks to see which blog post was requested by
//the user, and responds by rendering the associated HTML (with some
//additional information I chose to exclude from this post)
})

console.log(sitemap.generate(app))

这输出:

{ '/': [ 'get' ],
  '/:leg': [ 'get' ] }

什么时候应该输出:

{ '/': [ 'get' ],
  '/wild-birds': [ 'get' ],
  '/top-dogs-cats': [ 'get' ]
 }

我应该如何修复这个站点地图生成器?此外,您建议如何向用户提供更正后的 sitemap.xml?

express-sitemap 遍历所有已注册的路由以生成站点地图。在内部它调用:app._router.stack然后过滤所有路由。

您应该将您的帖子明确注册为路由,而不是使用参数。改为这样做:

posts.forEach(function(post) {
  app.get('/' + post.url, function(req, res, next) {
    res.render('post', {
      posts2: post
    });
    // your logic...
  });
});

然后调用 console.log(sitemap.generate(app)) returns 你所期望的:

{ '/': [ 'get' ],
  '/wild-birds': [ 'get' ],
  '/top-dogs-cats': [ 'get' ] }