pokemonblack1000 pokemonblack1000 - 3 months ago 40
Node.js Question

(Node/Express) Express-sitemap generating incorrect sitemap

I'm attempting to generate a sitemap for my website using the express-sitemap middleware. My code is as follows:

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))





This outputs:

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





When it should be outputting:

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





How should I go about fixing this sitemap generator? Additionally, how would you suggest serving the corrected sitemap.xml to the user?

Answer

express-sitemap iterates over all registered routes to generate the sitemap. Internally it calls: app._router.stack and then filters all routes.

You should register your posts explicitly as routes instead of using a parameter. Do this instead:

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

Then calling console.log(sitemap.generate(app)) returns what you'd expect:

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