Node.js: creare una sitemap di Google

Node.js: creare una sitemap di Google

In Node.js possiamo creare una sitemap per Google.

La soluzione è la seguente per i siti dinamici:


'use strict';

const express = require('express');
const mongoose = require('mongoose');

mongoose.Promise = Promise;
mongoose.connect('mongodb://user:password@127.0.0.1/mydb');

const port = process.env.PORT || 8080;
const app = express();
const Posts = require('Posts');
const BASEURL = 'http://www.esempio.com/';


app.get('/sitemap.xml', function(req, res) {
    

    Posts.find().then(function(posts) {

        let xml = '<?xml version="1.0" encoding="UTF-8"?>' + '\n';
        xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> ' + '\n';

        posts.forEach(function(post) {
            xml += ' <url>' + '\n';
            xml += '  <loc>' + BASEURL + post.slug + '</loc>' + '\n';
            xml += ' </url>' + '\n';
        });

        xml += '</urlset>';
        res.set('Content-Type', 'text/xml');
        res.send(xml);
        
    }).catch(function(err) {
       res.status(500).send('Error while creating the sitemap');
    });
    
});

app.listen(port);

Torna su