AJAX - Cross-Origin Resource Sharing (CORS) in AJAX

Cross-Origin Resource Sharing (CORS) is a security mechanism used by web browsers to control how web pages request resources from a different domain than the one that served the original page.

1. What is Same-Origin Policy

Before understanding CORS, it is important to know about the Same-Origin Policy.

The Same-Origin Policy is a browser security rule that prevents a web page from making requests to another domain unless permission is granted.

An origin consists of three parts:

  • Protocol (http or https)

  • Domain name

  • Port number

Example:

Without permission, AJAX requests between different origins are blocked by the browser.

2. Why CORS is Needed

Modern web applications frequently need data from external services such as APIs, payment gateways, or cloud servers.

Example:
A website running at https://mysite.com may need data from https://api.weather.com.

Because these are different origins, the browser blocks the request unless the server allows it using CORS.

3. How CORS Works

CORS allows servers to specify which origins are permitted to access their resources.

When an AJAX request is sent to another domain:

  1. The browser sends the request along with the Origin header.

  2. The server checks the request origin.

  3. The server responds with special headers indicating whether access is allowed.

  4. The browser allows or blocks the response based on these headers.

4. Important CORS Headers

Access-Control-Allow-Origin
Specifies which domain is allowed to access the resource.
Example:
Access-Control-Allow-Origin: https://mysite.com

Access-Control-Allow-Methods
Defines allowed HTTP methods such as GET, POST, PUT, DELETE.

Access-Control-Allow-Headers
Indicates which headers can be used in the request.

Access-Control-Allow-Credentials
Allows cookies or authentication data to be sent.

5. Types of CORS Requests

Simple Requests
These include basic GET or POST requests without custom headers. The browser directly sends the request.

Preflight Requests
For complex requests, the browser first sends an OPTIONS request to check server permissions before sending the actual request.

6. Example of AJAX Request with CORS

JavaScript code using Fetch API:

fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));

The server must allow the requesting origin for this request to succeed.

7. Server-Side CORS Configuration Example

Example using Node.js:

app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});

This configuration allows requests from any origin.

8. Common CORS Errors

CORS error messages usually appear in the browser console when:

  • The server does not allow the requesting domain.

  • Required headers are missing.

  • Credentials are used without permission.

These errors are browser security protections, not JavaScript coding errors.

9. Security Considerations

Allowing all origins using "*" can expose APIs to misuse. It is safer to allow only trusted domains.

Sensitive APIs should:

  • Restrict allowed origins

  • Validate authentication

  • Avoid exposing private data

10. Summary

CORS is a browser security feature that enables controlled communication between different websites. It allows AJAX applications to safely access external APIs while protecting users from unauthorized data access. Proper server configuration is required for successful cross-origin AJAX requests.