how do you add a cors header in node js code example
Example 1: access-control-allow-origin nodejs express
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
Example 2: 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')})