CORS explained
CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers that blocks web pages from making requests to a different domain than the one that served the web page. This is done to prevent malicious websites from making unauthorized requests on behalf of the user.
For example, if a web page served from example.com
tries to make an HTTP request to api.example.com
, the browser will block the request unless api.example.com
explicitly allows it. This is done by setting the Access-Control-Allow-Origin
header in the response to example.com
.
To allow a web page to make requests to a different domain, the server must include the Access-Control-Allow-Origin
header in its responses and set it to the origin of the web page. This can be done using the cors
module in Node.js.
Here is an example of how to use the cors
module in an express app:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
In this example, the cors
middleware is applied to the express app using the app.use()
method. This allows any web page to make requests to the server.
You can also configure the cors
middleware to only allow requests from specific origins by passing an options object to the cors()
function. For example:
app.use(cors({
origin: 'https://example.com'
}));
This would allow requests from https://example.com
, but block requests from all other origins.