Understanding the “No ‘Access-Control-Allow-Origin’ Header is Present” Error in JavaScript


Problem Statement

When making cross-origin API requests using JavaScript (e.g., via fetch or XMLHttpRequest), you might encounter this error:
“No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

This error occurs due to the Same-Origin Policy (SOP) enforced by browsers, which restricts cross-origin requests for security purposes. Interestingly, the same request works perfectly in Postman. Why? Let’s explore.


Solution Code

To resolve this issue, the server hosting the API must include specific CORS (Cross-Origin Resource Sharing) headers in its responses. Below are examples for different backends:


Node.js (Express) Example

npm install cors

const express \= require('express');  
const cors \= require('cors');

const app \= express();  
app.use(cors());

app.get('/api', (req, res) \=\> {  
    res.json({ message: 'CORS-enabled response' });  
});

app.listen(3000, () \=\> console.log('Server running on port 3000'));

Flask (Python) Example

pip install flask-cors

from flask import Flask  
from flask\_cors import CORS

app \= Flask(\_\_name\_\_)  
CORS(app)

@app.route('/api')  
def hello\_world():  
    return {'message': 'CORS-enabled response'}

PHP Example

\<?php  
header('Access-Control-Allow-Origin: \*');  
?\>

What Was Achieved?
By enabling CORS headers, browsers allow cross-origin API requests, resolving the error. The critical header to include is:

Access-Control-Allow-Origin: *

  • Alternatively, replace * with a specific origin URL (e.g., https://example.com) for enhanced security.

  • Why Does Postman Work?
    Postman doesn’t enforce the browser’s Same-Origin Policy (SOP). It directly sends HTTP requests without requiring or validating CORS headers.


Learn More

Additional Methods and Options

  1. Proxy Server
    Use a proxy server to handle cross-origin requests indirectly. For example, in a frontend app:
   fetch('/proxy/api');
  1. Browser Extensions
    During development, you can use Chrome extensions like “Allow-Control-Allow-Origin” to bypass CORS temporarily.

  2. Server-Side Preflight Requests
    Ensure the server handles OPTIONS requests correctly. These preflight requests are sent automatically for non-simple CORS requests.


Curious Cats 🐾

Why is SOP enforced only in browsers?
SOP is designed to protect browser-based interactions, particularly those involving cookies and session data, which browsers often send automatically. Non-browser clients like Postman don’t carry this risk, so they aren’t bound by SOP.


Summary

  1. Same-Origin Policy:
    SOP is a browser-enforced security feature that restricts cross-origin requests unless explicitly allowed via CORS headers.

  2. Postman Bypass:
    Postman doesn’t enforce SOP, so it can make requests without requiring CORS headers.

  3. Proper Fix:
    Always configure the server to send appropriate CORS headers. Avoid insecure practices like Access-Control-Allow-Origin: * in production unless absolutely necessary.


References


Quick Recap of CORS in JavaScript: Resolving “Access-Control-Allow-Origin” Errors and Future Insights

Thank you for reading this article and enhancing your understanding of the “No ‘Access-Control-Allow-Origin’ Header is Present” error in JavaScript. We hope it has clarified the concept of Same-Origin Policy (SOP) and how to resolve CORS-related issues effectively.

To expand your knowledge, here are five additional topics to explore:

  1. Preflight Requests: Learn how OPTIONS requests validate non-simple CORS requests and ensure your server handles them correctly.
  2. Credentialed Requests: Understand how to securely enable cross-origin requests that require authentication or cookies using Access-Control-Allow-Credentials.
  3. Specific Origins vs. Wildcard: Discover why defining specific origins is a more secure practice than using * in production environments.
  4. Debugging CORS Issues: Master debugging techniques with browser developer tools to quickly identify and resolve CORS errors.
  5. Security Best Practices: Dive into strategies to mitigate risks associated with poorly configured CORS and enhance API security.

Your journey as a developer is a continuous learning process, and overcoming challenges like CORS issues strengthens your skill set. Stay motivated, keep exploring, and strive to implement best practices in your projects.


Compiled by team Crio.Do