Impostazioni CORS in Node.js ed Express

Mattepuffo's logo
Impostazioni CORS in Node.js ed Express

Impostazioni CORS in Node.js ed Express

Ho creato una piccola web API in Node.js ed Express.

Impostato tutto, dal client ricevevo il solito errore su CORS.

Per impostare CORS su Express possiamo seguire due strade:

  • impostare gli header a mano
  • usare il modulo cors

La seconda opzione è quella che useremo.

Spostatevi nella cartella del vostro progetto e installate il modulo:

$ npm install --save cors

A questo punto ecco il codice per usarlo:

const express = require('express');

const app = express();
const cors = require('cors');
const port = 8080;

app.use(cors());

app.get('/', function (request, response, next) {
	// DO STUFF);
);

app.get('/:id', function (request, response, next) {
	// DO STUFF
);

app.listen(port);

Qui abbiamo abilitato tutte le opzioni riguardo CORS; e lo abbiamo abilitato su tutti i path.

Ovviamente possiamo anche usarlo singoli path, e impostare singole opzioni.

Io non ho provato in quanto mi serve questa configurazione; ve lo lascio come studio.

Enjoy!


Condividi

Commentami!