Could you explain the concept of CORS and why it is important in web development?
sobes.tech AI
Answer from AI
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from accessing resources located on a different domain (origin). By default, browsers block such requests to prevent attacks like Cross-Site Request Forgery (CSRF) and others.
CORS allows the server to explicitly specify which domains can access its resources through special HTTP headers, such as Access-Control-Allow-Origin.
Why is this important:
- It enables the creation of secure APIs accessible from different websites.
- It prevents unauthorized access to data.
- It provides control over who and how can use your resources.
Example: if a frontend on https://example.com makes an AJAX request to an API at https://api.example.org, the browser will first send a preflight OPTIONS request to check if the server permits such a request. If the server responds with the appropriate CORS headers, the browser will proceed with the main request.
In Node.js, CORS is often configured using middleware, such as the cors package:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: 'https://example.com' }));
app.get('/data', (req, res) => {
res.json({ message: 'Hello from API' });
});
app.listen(3000);