Postman
Access-Control-Allow-Origin
coding
javascript

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

The "No 'Access-Control-Allow-Origin' header is present on the requested resource" error occurs due to Cross-Origin Resource Sharing (CORS) restrictions enforced by web browsers. This behavior only applies to browser environments, which is why Postman does not encounter the same error.


Why Does This Happen?

  1. CORS Policy in Browsers:
    Modern browsers enforce the Same-Origin Policy for security reasons. If your JavaScript code (e.g., a fetch or XHR request) is making a request to a domain different from the one it originated from, the server needs to include appropriate CORS headers to allow the request.
    • If the server does not include the Access-Control-Allow-Origin header, the browser blocks the response.
  2. Postman Bypasses CORS:
    Postman (and similar tools like cURL) is not a browser and does not enforce CORS policies. This is why Postman can make requests to any server without restriction, regardless of the CORS headers.

How CORS Works

When your frontend JavaScript code makes an HTTP request to a server on a different origin (different domain, protocol, or port), the browser sends a preflight request (an OPTIONS request) to check if the server allows the cross-origin request.

To allow the request, the server must respond with appropriate CORS headers, such as:

  • Access-Control-Allow-Origin: Specifies which origins are allowed to access the resource.
    Example:
http
   Access-Control-Allow-Origin: *

or

http
Access-Control-Allow-Origin: https://example.com
  • Access-Control-Allow-Methods: Specifies allowed HTTP methods (e.g., GET, POST, etc.).
  • Access-Control-Allow-Headers: Specifies allowed headers.

If these headers are missing, the browser blocks the request and raises a CORS error.


Common Scenarios for the Error

  1. The Server Does Not Return CORS Headers:
    If the server does not include the Access-Control-Allow-Origin header in its response, the browser blocks the request.
  2. Mismatched Origins:
    • Your frontend is running on http://localhost:3000 and the server is on http://api.example.com.
    • Without proper CORS headers, the request fails.
  3. Preflight Request Failure:
    For non-simple requests (e.g., POST with custom headers), browsers send a preflight OPTIONS request. If the server does not handle the OPTIONS request properly, the main request fails.

How to Fix the Error

1. Modify Server-Side Code to Add CORS Headers

The server must include the appropriate CORS headers in its responses.

Allow All Origins (for development only):

Add the following header to the server's response:

http
Access-Control-Allow-Origin: *

Allow Specific Origins:

To allow requests only from a particular domain:

http
Access-Control-Allow-Origin: https://your-frontend-domain.com

Example for Node.js/Express:

javascript
1const express = require('express');
2const app = express();
3
4app.use((req, res, next) => {
5  res.header("Access-Control-Allow-Origin", "*"); // Allow all origins
6  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
7  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
8  next();
9});
10
11app.get('/', (req, res) => {
12  res.send('Hello, world!');
13});
14
15app.listen(3000, () => console.log('Server running on port 3000'));

2. Use a Proxy in Development

If you cannot modify the server, you can set up a proxy to forward your requests.

  • Frontend Proxy Example (React): In a React project using create-react-app, add a proxy to package.json:
json
   "proxy": "http://api.example.com"

This forwards all API requests to http://api.example.com, avoiding CORS issues.


3. Use Browser Extensions

For local development, you can use browser extensions to bypass CORS.

  • For example: "CORS Everywhere" (Firefox) or "Allow CORS" (Chrome).

⚠️ Caution: This is for development only. Do not rely on browser extensions in production.


4. Handle CORS Preflight Properly on the Server

Ensure that your server correctly handles OPTIONS preflight requests by including the appropriate CORS headers.


Summary

  • Why Postman Works: Postman does not enforce CORS policies because it is not a browser.
  • Why Browsers Block Requests: Browsers enforce CORS policies to protect users.
  • How to Fix: Modify the server to return appropriate CORS headers (Access-Control-Allow-Origin, etc.).

By configuring CORS correctly on the server, you can allow cross-origin requests and resolve the error.


Course illustration
Course illustration

All Rights Reserved.