To enable CORS (Cross-Origin Resource Sharing) in a Node.js application, you can use the cors middleware package. Here’s how you can do it:
First, install the cors package via npm
npm install cors
Once installed, you can use it in your Node.js application by requiring it and applying it to your Express application.
const express = require('express');
const cors = require('cors');
const app = express();
// Enable all CORS requests
app.use(cors());
// Or, to specify specific origins:
app.use(cors({
origin: 'http://example.com'
}));
const cors = require('cors') imports the cors middleware.
app.use(cors()) enables CORS for all routes in your Express application. You can pass options to cors() if you need to configure it further.
If you want to restrict CORS to specific origins, you can pass an options object to cors(). For example, app.use(cors({ origin: 'http://example.com' }))