Why doesn t Postman get a No Access-Control-Allow-Origin header is present on the requested resource error when my JavaScript code does

0 votes

I am trying to do authorization using JavaScript by connecting to the RESTful API built-in Flask. However, when I make the request, I get the following error:

XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

This is the request code:

$.ajax({
    type: "POST",
    dataType: 'text',
    url: api,
    username: 'user',
    password: 'pass',
    crossDomain : true,
    xhrFields: {
        withCredentials: true
    }
})
    .done(function( data ) {
        console.log("done");
    })
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
        alert(textStatus);
    });

I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?

Jun 8, 2020 in Java-Script by kartik
• 37,520 points
24,444 views

2 answers to this question.

0 votes

Hello @kartik,

It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:

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

If you are using Node-red you have to allow CORS in the node-red/settings.js file by un-commenting the following lines:

httpNodeCors: {
 origin: "*",
 methods: "GET,PUT,POST,DELETE"
},

If you are using Flask same as the question; you have first to install flask-cors

$ pip install -U flask-cors

Then include the Flask cors in your application.

from flask_cors import CORS

A simple application will look like:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

Hope it helps!

You can also ask if you have some more queries related to javascript or you can join our Java training class and ask the top instructors by yourself.

answered Jun 8, 2020 by Niroj
• 82,840 points
0 votes

Kartik,

I know this is far, far too late to be of help to you, but since the lone answer doesn't actually address your question at all, let me give it a crack. Prefaced warning, though: I'm going to oversimplify here, and use some hyperbole to help make this understandable. The technical details are correct, but the explanation is being simplified. 

IMPORTANT TLDR NOTE: this is long, so I wanna warn readers up front. This will not tell you how to get around CORS. This explains WTF we were thinking when we CREATED CORS, and how it became part of the browser, and why Postman et. al seem unaffected while Chrome/Firefox/IE/Edge all seem totally blocked by it.

Yanno... exactly what the OP's actual question was. There's plenty of articles on how to work around it. Few on why it exists at all.

WTF is CORS and who was the genius to add this crap to my internet?

Put very, very simply: CORS1 is NOT built in to ANY of the web specifications or protocols. There's NOTHING WRONG with one site pulling resources from another site, notwithstanding all the phishing, cracking, hacking, and hotlinking issues attendant therein. Okay, okay, I know that's a LOT to just hand-wave aside, but roll with me here for a second.

At the most basic level, underneath the browser, underneath the "www" part of the web, the actual mechanics that allow one "thingy" to talk to another "thingy" have no CORS provision built in. Indeed, that's kind how and why the internet WORKS, deep-down. We are CONSTANTLY pulling data from all over the place. Using NPM? Remote. Using a CDN? Remote. Using multiple sub-domains? Remote. Using a bloody LOAD-BALANCER (Docker/Kubernetes)? Remote. The internet NEEDS to be able to talk to other parts of itself. That's WHY it's a "NET" and not an "Inter-scatter-plot".

CORS is a BROWSER construct.

Let me repeat that: CORS is built into the WEB BROWSER, NOT the protocols that drive the internet. It's basically the result of all the big browser publishers sitting down in a room, all collusion-like3, and facing down the hacking and hotlinking problem statements from above. CORS was the outcome. 

Basically, someone piped up and said, "okay, fine. We agree the web has to talk to itself... and I should be able to let one of MY sites talk to ANOTHER one of MY sites... but I'm still getting financially raped on bandwidth costs because people keep hotlinking5 my images. So why don't we add a permission list at the SERVER6 level that says, 'the following web pages can pull resources from me'? We can use the message headers - those allow the browser to talk to the server already - to let people add a whitelist if they want to, and we can make it so by default it's off, so it doesn't break www as it's implemented now!" 

Seems reasonable, right? Clever, easy fix... pretty much handles the issue... doesn't break anything existing, backwards-compatible... all nice and tidy. And so it was agreed: they found their fix. And they all - Firefox, Chrome, IE, Safari, Opera, you name it - went home and stuffed that new rule in. That's what that Access-Control-Allow-Origin="*" does.

So how come Postman/cURL/wget/mobile devices don't have CORS issues?

Simple: They're. Not. Browsers. The groups that code/maintain those utilities and tools weren't AT that meeting. Weren't invited or didn't exist at the time. Weren't necessary7. Postman uses the raw tools and protocols (cURL, I think in PM's case) to retrieve its results. So it's not LOOKING for the headers that say "only the following sites are okay." Oh, it SEES em, sure. "But that's a browser thing. Not our problem."

But it says to allow "*"! That's a wildcard! Why do I keep getting blocked!?

Well, one of two reasons, typically: either
1. you're trying to pull data or content from a server/site that ISN'T yours. See everything above (Google, for instance, will parry most requests except to certain subdomains).
2. You DO own the site you're trying to import files from, but you're also passing credentials.

Without going into a bunch of history or technobabble as to why this is the case, if your request requires some form of authentication (user has to be logged in, request needs SSO, user requires a token/JWT/SAML/etc, etc.). I want to stress this next bit: 

The default behavior of the browser is to block ANY AND ALL requests that says allow "*" when credentials are also being used

It wasn't always that way; it came up out of necessity. Suffice it to say that it was added to obviate some hinky workarounds (certain ways of making requests that ignored the headers, Flash, one great loophole involving JSONP files, browser extensions, etc.), as well as some outright hacks that compromised the security of said credentials. So really it's the hackers' faults9. Though, admittedly: we only hacked around CORS because it's a pain in the ass... which wouldn't have been necessary at all if it weren't for morons who didn't grasp how bandwidth works10.

So what stops me from coding my OWN browser without the CORS rules in it?

Nothing. Not a damn thing. Knock yourself out. Give my regards to Konqueror, Lynx, Camino, Galeon, Bento, Maxthon, Avant, Baidu, Dolphin, Midori, Otter, Roccat, Torch, Brave, Mosaic, UC, WebbIE, AOL, and NetTV when you get there. Not to Opera, though (screw you, Opera). Good luck with the whole "telling your boss/client that it works, but only if the customer downloads and installs this special browser" thing, too.

Okay... what about middleware!? What if I wrote a program that uses cURL or PHP or whatever to perform the request but strips the headers off before it hands it back to the browser!?

Congratulations. You've just invented the other answer on this site to this question. And cors-anywhere. And bypass-cors. And, and, and... but it's still solving the wrong problem. The reason solutions like that work at all? They're just not a big enough threat to be worth the time and energy to stamp out. Besides, they're either not really viable in a production environment (cors-anywhere, et al) or they're really just another way of addressing the correct solution - simply modifying the cors headers on the server - with a DIFFERENT solution that still offers the same financial security to the website owners (the php header fix).

Hope this helps you or someone to follow.

@JJ - Nerdy Deeds, LLC


  1. Cross-Origin Resource Sharing2
  2. One of the BANES of my existence as a Senior FED
  3. Don't look surprised: this happens ALL THE TIME. And speaking as someone who's been a web engineer since the mid 90s? Trust me: its better they do4
  4. Like, way, WAY better. Truly: you have NO idea. It used to be standard practise to code everything 2-3 times to accommodate the different browser rendering engines. Got it working in IE? Great! Now write the Mozilla version.
  5. I keep using that term, assuming everyone knows what it means. Sorry. "Hotlinking" refers to the practise of using a file on MY webpage hosted on YOUR server. I could put <img src="https://your-domain.com/some-2mb-image.jpg" /> on my page and YOU got to pay the bandwidth cost. If my page was hugely popular and yours wasn't? Nyah-nyah.
  6. It has to be at the server level, or I could just flip the flag in Dev Tools, of course.
  7. If there has ever been a case of a POSTMAN collection facilitating a DDOS attack or costing someone ELSE tens of thousands of dollars in bandwidth, I'VE never heard of it8
  8. I, personally, have received a $12,500 bill from my hosting company though, due to people hotlinking images from my site into their MySpace pages. Almost put my little two-man shop outta business that year.
  9. We're10 why you can't have nice things.
  10. Okay, so maybe THEY'RE why you can't have nice things.
answered May 19, 2021 by Nerdy Deeds, LLC

edited Mar 5
0 votes

My understanding is that you are using a different domain than the one your page is present on by using the XMLHttpRequest. This is enabling the blocking of it due to the reason that it normally permits a request for security reasons in the same origin. You will have to try a different method in order to enhance a cross-domain request. Share your credentials with CORS and then Add credentials: 'include' to the fetch options like mentioned below. This will include the cookie with the request.

fetch('https://example.com', {

 mode: 'cors',

 credentials: 'include'

})

Access-Control-Allow-Origin must be set to a specific origin (no wildcard using *) and must set Access-Control-Allow-Credentials to true.

HTTP/1.1 200 OK

Access-Control-Allow-Origin: https://example.com

Access-Control-Allow-Credentials: true

answered Feb 9, 2022 by Soham
• 9,710 points

Related Questions In Java-Script

0 votes
1 answer

How to find event listeners on a DOM node when debugging or from the JavaScript code?

Hii @kartik, It is possible to list all ...READ MORE

answered Jun 8, 2020 in Java-Script by Niroj
• 82,840 points
129,018 views
0 votes
1 answer

Error:Origin is not allowed by Access-Control-Allow-Origin

Hello @kartik, The easiest way to handle this ...READ MORE

answered Jun 18, 2020 in Java-Script by Niroj
• 82,840 points
9,182 views
0 votes
0 answers

How does Access-Control-Allow-Origin header work?

Until now my understanding of its semantics ...READ MORE

May 11, 2022 in Java-Script by Kichu
• 19,040 points
973 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,840 points
23,446 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,840 points
3,135 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23, 2020 in Laravel by Niroj
• 82,840 points
3,167 views
+1 vote
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23, 2020 in Laravel by Niroj
• 82,840 points
45,587 views
0 votes
1 answer

Error:No Access-Control-Allow-Origin header is present on the requested resource node.js

Hello @kartik, My guess is that you're serving ...READ MORE

answered Jun 8, 2020 in Java-Script by Niroj
• 82,840 points
4,833 views
0 votes
1 answer

Error:Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers

Hello @kartik, Access-Control-Allow-Headers does not allow * as accepted value. Instead of ...READ MORE

answered Jul 6, 2020 in Java-Script by Niroj
• 82,840 points
2,608 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP