MEHDI.
RETURN_TO_INDEX

Understanding CORS: Why Your API Requests Fail in the Browser

4 min read
#Security#Web Development#JavaScript#API

Introduction to CORS

As a frontend developer, you may have encountered issues when making API requests from your web application to a server hosted on a different domain. This is due to a security feature implemented in web browsers called Cross-Origin Resource Sharing, or CORS for short. In this article, I will explain what CORS is, how it works, and provide examples using Express.js to help you understand and resolve common issues.

What is CORS?

CORS is a security feature that restricts web pages from making requests to a different origin (domain, protocol, or port) than the one the web page was loaded from. This is done to prevent malicious scripts from making unauthorized requests on behalf of the user. For example, if a user is logged into their bank's website and visits a malicious website, the malicious website should not be able to make requests to the bank's website on behalf of the user.

How CORS Works

When a web page makes a request to a different origin, the browser sends an OPTIONS request, known as a preflight request, to the server before sending the actual request. The preflight request includes headers that specify the method and headers of the actual request. The server then responds with headers that specify which methods and headers are allowed.

Preflight Requests

Preflight requests are sent by the browser before making a request to a different origin. The preflight request includes the following headers:

  • Access-Control-Request-Method: specifies the method of the actual request
  • Access-Control-Request-Headers: specifies the headers of the actual request

The server responds with the following headers:

  • Access-Control-Allow-Origin: specifies which origins are allowed to make requests
  • Access-Control-Allow-Methods: specifies which methods are allowed
  • Access-Control-Allow-Headers: specifies which headers are allowed
  • Access-Control-Max-Age: specifies how long the preflight response is valid

Example with Express.js

Here is an example of how to handle CORS in an Express.js application:

const express = require('express');
const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
    res.header('Access-Control-Max-Age', '3600');
    return res.status(200).send();
  }
  next();
});

app.get('/api/data', (req, res) => {
  res.send({ message: 'Hello from server' });
});

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

In this example, we are using the res.header() method to set the CORS headers. We are also handling the OPTIONS request by checking if the request method is 'OPTIONS' and sending a response with the allowed methods and max age.

Common Mistakes

One common mistake is not handling the preflight request correctly. Make sure to send a response with the allowed methods and headers when the request method is 'OPTIONS'.

Another common mistake is not setting the Access-Control-Allow-Origin header to the correct value. If you want to allow requests from all origins, you can set this header to '*'. However, if you want to allow requests from only a specific origin, you should set this header to that origin.

Practical Takeaways

To avoid issues with CORS, make sure to:

  • Handle preflight requests correctly by sending a response with the allowed methods and headers
  • Set the Access-Control-Allow-Origin header to the correct value
  • Use the res.header() method to set the CORS headers in Express.js
  • Test your API requests in the browser to ensure they are working as expected