Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate a sitemap in expressjs

I downloaded my XML sitemap from the sitemap xml generator website. I placed my sitemap.xml on my public directory but when I tried to submit the sitemap.xml into google console i received the following error: General HTTP error: 404 not found HTTP Error: 404
So i coded
app.get('/sitemap.xml', function( req, res, next ) { res.header('Content-Type', 'text/xml'); res.render( 'sitemap' ); )};

And when i navigate to the 'website/sitemap.xml' I am getting the following error:

This page contains the following errors:

error on line 1 at column 42: Specification mandate value for attribute itemscope

Thanks for your help

like image 896
Vic B-A Avatar asked May 12 '16 18:05

Vic B-A


3 Answers

Generate your sitemap.xml file using a tool like https://www.xml-sitemaps.com/

upload the sitemap.xml in your project

then add this to your .js file:

router.get('/sitemap.xml', function(req, res) {
res.sendFile('YOUR_PATH/sitemap.xml');
});

make sure you change YOUR_PATH for the actual path where your sitemap.xml file is.

like image 92
Louis Chaussé Avatar answered Sep 29 '22 14:09

Louis Chaussé


Sitemaps do not have to be XML documents. A simple text file with URLs is all you need so something like below works fine. In the following example, fetchMyUrls() would be a function/method that asynchronously gets and returns the available URLs as an array of strings (URL strings).

async function index (req, res){
    return fetchMyUrls().then((urls) => {
      var str = '';
      for (var url of urls) {
        str = str + url + '\n';
      }
      res.type('text/plain');
      return res.send(str);
    });  
}
like image 33
Ronnie Royston Avatar answered Sep 29 '22 14:09

Ronnie Royston


For those looking for a way to create the XML dynamically on your code and don't want to use another library nor have a file stored in the public folder, you can use this:

app.get('/sitemap.xml', async function(req, res, next){
  let xml_content = [
    '<?xml version="1.0" encoding="UTF-8"?>',
    '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
    '  <url>',
    '    <loc>http://www.example.com/</loc>',
    '    <lastmod>2005-01-01</lastmod>',
    '  </url>',
    '</urlset>'
  ]
  res.set('Content-Type', 'text/xml')
  res.send(xml_content.join('\n'))
})
like image 36
Ñhosko Avatar answered Sep 29 '22 14:09

Ñhosko