1var allowedOrigins = ['http://localhost:3000', 'http://yourapp.com'];
2app.use(cors({
3 origin: function(origin, callback){
4 // allow requests with no origin
5 // (like mobile apps or curl requests)
6 if(!origin)
7 return callback(null, true);
8 if(allowedOrigins.indexOf(origin) === -1){
9 var msg = 'The CORS policy for this site does not ' +
10 'allow access from the specified Origin.';
11 return callback(new Error(msg), false);
12 }
13 return callback(null, true);
14 }
15}));
1installation :
2
3$ npm i cors
4
5usage :
6
7var express = require('express')
8var cors = require('cors')
9var app = express()
10
11app.use(cors())
12
13app.get('/products/:id', function (req, res, next) {
14 res.json({msg: 'This is CORS-enabled for all origins!'})
15})
16
17app.listen(80, function () {
18 console.log('CORS-enabled web server listening on port 80')
19})
20
1var express = require('express')var cors = require('cors')var app = express() app.get('/products/:id', cors(), function (req, res, next) { res.json({msg: 'This is CORS-enabled for a Single Route'})}) app.listen(80, function () { console.log('CORS-enabled web server listening on port 80')})
1var express = require('express')var cors = require('cors')var app = express() app.use(cors()) app.get('/products/:id', function (req, res, next) { res.json({msg: 'This is CORS-enabled for all origins!'})}) app.listen(80, function () { console.log('CORS-enabled web server listening on port 80')})