1var express = require('express')
2var cors = require('cors')
3var app = express()
4
5app.use(cors())
6
7app.get('/products/:id', function (req, res, next) {
8 res.json({msg: 'This is CORS-enabled for all origins!'})
9})
10
11app.listen(80, function () {
12 console.log('CORS-enabled web server listening on port 80')
13})
14
1// npm i cors
2
3// Import cors
4const cors = require("cors");
5
6// Allowed origins
7const allowedOrigins = ["http://localhost:8100", "https://yourapp.com"];
8
9// Do you want to skip the checking of the origin and grant authorization?
10const skipTheCheckingOfOrigin = true;
11
12// MIDDLEWARES
13app.use(
14 cors({
15 origin: function (origin, callback) {
16 // allow requests with no origin (like mobile apps or curl requests)
17 // or allow all origines (skipTheCheckingOfOrigin === true)
18 if (!origin || skipTheCheckingOfOrigin === true) return callback(null, true);
19
20 // -1 means that the user's origin is not in the array allowedOrigins
21 if (allowedOrigins.indexOf(origin) === -1) {
22 var msg =
23 "The CORS policy for this site does not " +
24 "allow access from the specified Origin.";
25
26 return callback(new Error(msg), false);
27 }
28 // origin is in the array allowedOrigins so authorization is granted
29 return callback(null, true);
30 },
31 })
32);
1var express = require('express')
2var cors = require('cors') //use this
3var app = express()
4
5app.use(cors()) //and this
6
7app.get('/user/:id', function (req, res, next) {
8 res.json({user: 'CORS enabled'})
9})
10
11app.listen(5000, function () {
12 console.log('CORS-enabled web server listening on port 5000')
13})
1// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
2
3app.all('*', function(req, res, next) {
4 res.header("Access-Control-Allow-Origin", "*");
5 res.header("Access-Control-Allow-Headers", "X-Requested-With");
6 res.header('Access-Control-Allow-Headers', 'Content-Type');
7 next();
8});
9
1app.use(function(req, res, next) {
2 res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD"); // update to match the domain you will make the request from
3 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
4 next();
5});
1var allowedOrigins = ['http://localhost:3000',
2 'http://yourapp.com'];
3app.use(cors({
4 origin: function(origin, callback){
5 // allow requests with no origin
6 // (like mobile apps or curl requests)
7 if(!origin)
8 return callback(null, true);
9 if(allowedOrigins.indexOf(origin) === -1){
10 var msg = 'The CORS policy for this site does not ' +
11 'allow access from the specified Origin.';
12 return callback(new Error(msg), false);
13 }
14 return callback(null, true);
15 }
16}));