Cross-Origin Resource Sharing

·

2 min read

If you are a front-end developer or API developer, you have come across this term many times, so let's discuss it.

CORS stands for "Cross-Origin Resource Sharing."

In simple words, it is a security mechanism that is implemented by web browsers to make the web page more secure. It is a header-based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

CORS provides a mechanism for servers to specify which origins are allowed to access their resources. When a web page makes a cross-origin request, the browser includes an additional HTTP header called "Origin" that specifies the origin of the requesting page. The server, in turn, can include an "Access-Control-Allow-Origin" response header that indicates which origins are allowed to access the requested resource.

Here's an example to show how to set headers and how to make a Cors request from the front end.

  • Front-End
const apiUrl = 'https://api.example.com'; // Backend URL
// Make a cross-origin request to the API
fetch(apiUrl, {
  method: 'GET',
  headers: {
    'Origin': 'https://yourfrontenddomain.com' 
    // Front-end domain URL
  }
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Request failed.');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });
  • Back-End
const express = require('express');
const app = express();

// Enable CORS for all routes
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'https://yourfrontenddomain.com'); // Replace with your front-end domain
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Credentials', 'true'); // If you want to allow sending credentials (e.g., cookies)
  next();
});

// Define your API routes
app.get('/api/data', (req, res) => {
  res.json({ message: 'This is the API response.' });
});

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

Preflight :

Before making an actual request to the server, the browser makes a request to the server hosting the cross-origin resource (back-end), in order to check that the server will permit the actual request. This is called a preflight request.

Below is a pictorial representation of how the Cors process works.

  1. The browser makes a preflight request

  2. The server sends a preflight response.