Node.js: abilitare CORS

Node.js: abilitare CORS

In questo articolo vedremo come abilitare CORS in Node.js.

Dobbiamo aggiungere gli header HTTP Access-Control-Allow-Origin e Access-Control-Allow-Headers ad ogni richiesta HTTP o ad un gruppo di richieste che andremo a gestire nella nostra applicazione.


'use strict';

const https = require('https');

const fs = require('fs');

const PORT = process.env.PORT || 8000;

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200, {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
  });
  res.end(JSON.stringify({
     version: '1.0',
     endpoint: req.url,
     method: req.method,
     headers: req.headers 
  }, null, 2));
}).listen(PORT);

Quindi possiamo eseguire il seguente test lato client.


(function() {
    fetch('https://api.tld/test')
    .then(response => response.json())
    .then(data => console.log(data));
})();   

Torna su