npm cors package code example
Example 1: allow cross origin node
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Example 2: cors npm
/*
Installation
$ npm install cors
*/
// Simple Usage (Enable All CORS Requests)
var 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");
});
Example 3: cors express
var allowedOrigins = ['http://localhost:3000',
'http://yourapp.com'];
app.use(cors({
origin: function(origin, callback){
// allow requests with no origin
// (like mobile apps or curl requests)
if(!origin)
return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
var msg = 'The CORS policy for this site does not ' +
'allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));
Example 4: cors package install npm
var 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')})
Example 5: cors package install npm
var 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')})