Cross-Origin Resource Sharing (CORS) is a security feature that allows web applications to make requests to domains different from the one that served the web page. This guide will help you understand how to configure CORS on your web server.
Basic Concepts
- Origin: The URL of the web page making the request.
- Resource: The URL of the server resource being requested.
- Response: The data sent back from the server to the web page.
CORS Headers
- Access-Control-Allow-Origin: Indicates whether the resource can be shared with the origin.
- Access-Control-Allow-Methods: Specifies the HTTP methods allowed when accessing the resource.
- Access-Control-Allow-Headers: Specifies the HTTP headers that can be used when making the request.
Configuration Steps
- Enable CORS on Your Server: Most modern web servers have CORS middleware or plugins available. For example, you can use
cors
middleware in Node.js. - Configure the CORS Headers: Set the appropriate CORS headers for your server.
- Test Your Configuration: Use tools like
curl
or Postman to test your CORS configuration.
Example
Here's an example of how to configure CORS in Node.js using the cors
middleware:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: 'https://example.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.get('/data', (req, res) => {
res.json({ message: 'Hello, World!' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Additional Resources
For more information on CORS, please refer to the following resources:
Express.js Logo