Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers, which doesn’t allow requests to be made to a different domain than the one hosting the web page (the origin) unless the other domain explicitly allows it. To handle CORS in a Node.js application, you can configure your server to set specific HTTP headers, especially the ‘Access-Control-Allow-Origin‘ header.
Here’s a detailed explanation with a couple of examples.
There are two common ways to handle CORS in a Node.js application:
1. Manually adding headers
2. Using the ‘cors‘ middleware package with Express.js
**1. Manually adding headers**
Consider the following example using the built-in ‘http‘ module in Node.js:
const http = require("http");
const server = http.createServer((req, res) => {
// Set CORS headers
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
// Handle request
res.write("Hello, CORS is enabled!");
res.end();
});
server.listen(3000, () => {
console.log("Server is listening on port 3000...");
});
In this example, we manually set CORS headers on the response object. The ‘"*"` in ‘"Access-Control-Allow-Origin"` header allows any domain to access your server. You can replace ‘"*"` with a specific domain (e.g., ‘"http://my-domain.com"`) to restrict access to that domain only.
**2. Using the ‘cors‘ middleware package with Express.js**
For Node.js applications using the Express.js framework, you can handle CORS using the ‘cors‘ middleware package. First, install the package:
npm install cors
Here’s an example configuration:
const express = require("express");
const cors = require("cors");
const app = express();
// Configure CORS Middleware
const corsOptions = {
origin: "*", // or a specific domain, e.g., 'http://my-domain.com'
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type"],
};
// Enable CORS on all routes
app.use(cors(corsOptions));
// Simple route
app.get("/", (req, res) => {
res.send("Hello, CORS is enabled!");
});
app.listen(3000, () => {
console.log("Server is listening on port 3000...");
});
In this example, we initialized the CORS middleware with a configuration object and added it to the Express app using ‘app.use(cors(corsOptions))‘.
CORS is now enabled for your Node.js application. You can adjust the ‘origin‘, ‘methods‘, and ‘allowedHeaders‘ properties in the ‘corsOptions‘ object as needed for your application’s security requirements.
Remember that these configurations only allow CORS in your Node.js application. Ensure you also handle CORS on the client-side, e.g., by adding the ‘crossorigin‘ attribute to your HTML tags.