Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aungthuoo/d1818cd12ce5221075d89659f620a00d to your computer and use it in GitHub Desktop.
Save aungthuoo/d1818cd12ce5221075d89659f620a00d to your computer and use it in GitHub Desktop.

To enable Cross-Origin Resource Sharing (CORS) in a Node.js application

// Example 1 : To enable CORS in single route

app.get("/api/records", function(req, res) {
    res.append("Access-Control-Allow-Origin", "*");
    res.append("Access-Control-Allow-Methods", "*");
    res.append("Access-Control-Allow-Headers", "*");
    //…
});

// Example 2 : To enable CORS in all route

app.use(function(req, res, next) {
    res.append("Access-Control-Allow-Origin", "*");
    res.append("Access-Control-Allow-Methods", "*");
    res.append("Access-Control-Allow-Headers", "*");
    next();
});

//Example 3 : To enable CORS with package // Install the "cors" package:

npm install cors

// index.js

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

// Enable CORS for all routes (for any origin)
app.use(cors());

// Define your API routes or middleware here
app.get('/api/data', (req, res) => {
  // Your API logic here
  res.json({ message: 'This is an example API response.' });
});

app.listen(port, () => {
  console.log(`Server is running on port port`);
});


// for specific origin 
/*
const corsOptions = {
  origin: ['https://example1.com', 'https://example2.com'],
};

*/
const corsOptions = {
  origin: 'https://example.com', // Replace with the desired origin
};
app.use(cors(corsOptions));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment