Skip to content
Fix Code Error

No ‘Access-Control-Allow-Origin’ header is present on the requested resource—when trying to get data from a REST API

March 13, 2021 by Code Error
Posted By: Anonymous

I’m trying to fetch some data from the REST API of HP Alm. It works pretty well with a small curl script – I get my data.

Now doing that with JavaScript, fetch and ES6 (more or less) seems to be a bigger issue. I keep getting this error message:

Fetch API cannot load . Response to preflight request doesn’t
pass access control check: No ‘Access-Control-Allow-Origin’ header is
present on the requested resource. Origin ‘http://127.0.0.1:3000‘ is
therefore not allowed access. The response had HTTP status code 501.
If an opaque response serves your needs, set the request’s mode to
‘no-cors’ to fetch the resource with CORS disabled.

I understand that this is because I am trying to fetch that data from within my localhost and the solution should be using CORS. Now I thought I actually did that, but somehow it either ignores what I write in the header or the problem is something else?

So, is there an implementation issue? Am I doing it wrong? I can’t check the server logs unfortunately. I’m really a bit stuck here.

function performSignIn() {

  let headers = new Headers();

  headers.append('Content-Type', 'application/json');
  headers.append('Accept', 'application/json');

  headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
  headers.append('Access-Control-Allow-Credentials', 'true');

  headers.append('GET', 'POST', 'OPTIONS');

  headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));

  fetch(sign_in, {
      //mode: 'no-cors',
      credentials: 'include',
      method: 'POST',
      headers: headers
    })
    .then(response => response.json())
    .then(json => console.log(json))
    .catch(error => console.log('Authorization failed : ' + error.message));
}

I am using Chrome. I also tried using that Chrome CORS Plugin, but then I am getting another error message:

The value of the ‘Access-Control-Allow-Origin’ header in the response
must not be the wildcard ‘*’ when the request’s credentials mode is
‘include’. Origin ‘http://127.0.0.1:3000‘ is therefore not allowed
access. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.

Solution

This answer covers a lot of ground, so it’s divided into three parts:

  • How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems
  • How to avoid the CORS preflight
  • How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems

How to use a CORS proxy to avoid “No Access-Control-Allow-Origin header” problems

If you don’t control the server your frontend code is sending a request to, and the problem with the response from that server is just the lack of the necessary Access-Control-Allow-Origin header, you can still get things to work—by making the request through a CORS proxy.

You can easily run your own proxy using code from https://github.com/Rob–W/cors-anywhere/.
You can also easily deploy your own proxy to Heroku in just 2-3 minutes, with 5 commands:

git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master

After running those commands, you’ll end up with your own CORS Anywhere server running at, e.g., https://cryptic-headland-94862.herokuapp.com/.

Now, prefix your request URL with the URL for your proxy:

https://cryptic-headland-94862.herokuapp.com/https://example.com

Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:

  1. Forwards the request to https://example.com.
  2. Receives the response from https://example.com.
  3. Adds the Access-Control-Allow-Origin header to the response.
  4. Passes that response, with that added header, back to the requesting frontend code.

The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.

This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS request, because in that case, the proxy also sends back the Access-Control-Allow-Headers and Access-Control-Allow-Methods headers needed to make the preflight successful.


How to avoid the CORS preflight

The code in the question triggers a CORS preflight—since it sends an Authorization header.

https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

Even without that, the Content-Type: application/json header would also trigger a preflight.

What “preflight” means: before the browser tries the POST in the code in the question, it’ll first send an OPTIONS request to the server — to determine if the server is opting-in to receiving a cross-origin POST that has Authorization and Content-Type: application/json headers.

It works pretty well with a small curl script – I get my data.

To properly test with curl, you must emulate the preflight OPTIONS request the browser sends:

curl -i -X OPTIONS -H "Origin: http://127.0.0.1:3000" 
    -H 'Access-Control-Request-Method: POST' 
    -H 'Access-Control-Request-Headers: Content-Type, Authorization' 
    "https://the.sign_in.url"

…with https://the.sign_in.url replaced by whatever your actual sign_in URL is.

The response the browser needs to see from that OPTIONS request must have headers like this:

Access-Control-Allow-Origin:  http://127.0.0.1:3000
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type, Authorization

If the OPTIONS response doesn’t include those headers, then the browser will stop right there and never even attempt to send the POST request. Also, the HTTP status code for the response must be a 2xx—typically 200 or 204. If it’s any other status code, the browser will stop right there.

The server in the question is responding to the OPTIONS request with a 501 status code, which apparently means it’s trying to indicate it doesn’t implement support for OPTIONS requests. Other servers typically respond with a 405 “Method not allowed” status code in this case.

So you’re never going to be able to make POST requests directly to that server from your frontend JavaScript code if the server responds to that OPTIONS request with a 405 or 501 or anything other than a 200 or 204 or if doesn’t respond with those necessary response headers.

The way to avoid triggering a preflight for the case in the question would be:

  • if the server didn’t require an Authorization request header but instead, e.g., relied on authentication data embedded in the body of the POST request or as a query param
  • if the server didn’t require the POST body to have a Content-Type: application/json media type but instead accepted the POST body as application/x-www-form-urlencoded with a parameter named json (or whatever) whose value is the JSON data

How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems

I am getting another error message:

The value of the ‘Access-Control-Allow-Origin’ header in the response
must not be the wildcard ‘*’ when the request’s credentials mode is
‘include’. Origin ‘http://127.0.0.1:3000’ is therefore not allowed
access. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.

For a request that includes credentials, browsers won’t let your frontend JavaScript code access the response if the value of the Access-Control-Allow-Origin response header is *. Instead the value in that case must exactly match your frontend code’s origin, http://127.0.0.1:3000.

See Credentialed requests and wildcards in the MDN HTTP access control (CORS) article.

If you control the server you’re sending the request to, then a common way to deal with this case is to configure the server to take the value of the Origin request header, and echo/reflect that back into the value of the Access-Control-Allow-Origin response header; e.g., with nginx:

add_header Access-Control-Allow-Origin $http_origin

But that’s just an example; other (web) server systems provide similar ways to echo origin values.


I am using Chrome. I also tried using that Chrome CORS Plugin

That Chrome CORS plugin apparently just simplemindedly injects an Access-Control-Allow-Origin: * header into the response the browser sees. If the plugin were smarter, what it would be doing is setting the value of that fake Access-Control-Allow-Origin response header to the actual origin of your frontend JavaScript code, http://127.0.0.1:3000.

So avoid using that plugin, even for testing. It’s just a distraction. To test what responses you get from the server with no browser filtering them, you’re better off using curl -H as above.


As far as the frontend JavaScript code for the fetch(…) request in the question:

headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');

Remove those lines. The Access-Control-Allow-* headers are response headers. You never want to send them in a request. The only effect that’ll have is to trigger a browser to do a preflight.

Answered By: Anonymous

Related Articles

  • Using less in a polymer-dart application
  • Vue js vuecli3 application does not work in ie11…
  • Error using core-scaffold from polymer JS in the…
  • XMLHttpRequest cannot load ✘✘✘ No…
  • AppCompat v7 r21 returning error in values.xml?
  • Why does an OPTIONS request fail when the answer to…
  • How does Access-Control-Allow-Origin header work?
  • How to use html template with vue.js
  • What is the incentive for curl to release the…
  • Error: container has not been made global - how to solve?
  • Angular: Can't find Promise, Map, Set and Iterator
  • Windows could not start the Apache2 on Local…
  • What does do?
  • Simplest way to create Unix-like continuous pipeline…
  • sql query to find priority jobs
  • How can I send ajax POST on browser?
  • Integrating JSON feed with Backbone JS
  • How do I approach solving this problem: Cannot…
  • CORS error even after setting…
  • Request header field Authorization is not allowed by…
  • curl -GET and -X GET
  • Why Chrome can’t set cookie
  • How do I measure request and response times at once…
  • Validation failed for one or more entities. See…
  • don't know what went wrong nav bar with Tailwind CSS…
  • CORS error using Aurelia Fetch client
  • What does this symbol mean in JavaScript?
  • CORS - How do 'preflight' an httprequest?
  • CORS error despite Access-Control-Allow-Origin…
  • render function or template not defined in…
  • error LNK2005: ✘✘✘ already defined in…
  • Access-Control-Allow-Origin is not allowed by…
  • How can I discover the issuer of an opaque access token?
  • How can you debug a CORS request with cURL?
  • How to support HTTP OPTIONS verb in ASP.NET…
  • Why do git fetch origin and git fetch : behave differently?
  • Solve Cross Origin Resource Sharing with Flask
  • Unexpected end of JSON input while parsing
  • getting error while updating Composer
  • Remove complete node from XML, if the child…
  • What are access specifiers? Should I inherit with…
  • How to connect my server with my ember cli App
  • Breaking on exception: type 'HtmlElement' is not a…
  • Group array of objects by multiple keys using d3.groups
  • How do I include a JavaScript file in another…
  • JavaScript - XMLHttpRequest,…
  • Using useEffect and useContext while fetching data
  • Ways to circumvent the same-origin policy
  • Geolocation denied for HTML embedded site - anchor…
  • Node Api Doesn't Respond To Postman or through…
  • Why call git branch --unset-upstream to fixup?
  • How to convert this curl command to JavaScript's fetch
  • Curl not recognized as an internal or external…
  • CORS: Cannot use wildcard in…
  • Ember.js set initial value of property
  • How to get a cross-origin resource sharing (CORS)…
  • How do I set response headers in Flask?
  • Simple C example of doing an HTTP POST and consuming…
  • Ways to save Backbone.js model data?
  • Issue adding access token to header in Backbone: It…
  • CORS error :Request header field Authorization is…
  • Aurelia Post with http-fetch-client producing an…
  • Why do I have to "git push --set-upstream origin "?
  • Django, Next.JS: CORS header…
  • How to secure EmberJS or any Javascript MVC framework?
  • "Access-Control-Allow-Origin" CORS issue when using…
  • Access-Control-Allow-Origin error in ember.js
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Ajax - "Access-Control-Allow-Origin" error in ember.js
  • Uncaught (in promise) TypeError: Failed to fetch and…
  • Reading JSON POST using PHP
  • What is an opaque response, and what purpose does it serve?
  • Has been blocked by CORS policy: Response to…
  • Start redis-server with config file
  • yeoman generator-ember doesn't show anything in browser
  • vue socket.io connection attempt returning "No…
  • Vue.js frontend interacting with Flask backend CORS…
  • Ember test fail with `testem.js not loaded?`
  • How can I integrate javascript hot reload into…
  • Fastest way to iterate over all the chars in a String
  • Express Session not persisting after CORS calls
  • How can I run multiple curl requests processed sequentially?
  • HTTP Basic Authentication - what's the expected web…
  • Why is it common to put CSRF prevention tokens in cookies?
  • Laravel frontend to Django backend x-csrf-token not…
  • libcurl/C : when can I free header and postdata buffers?
  • how to fix 'Access to XMLHttpRequest has been…
  • cors issue with vue and dotnet
  • Cross Domain Request w/ Cors
  • How can I configure Storybook.js Webpack with…
  • CORS Authorization polymer and goapp golang
  • CORS errors on Azure Translator API (Cognitive…
  • How do I POST JSON data with cURL?
  • .Net Core 3.1 deploy on Centos 7
  • Backbone POST JSON
  • How to use Servlets and Ajax?
  • Aurelia Windows Authentication - Post 401 Unauthorized
  • Vuex Axios CORS Block Acess-control-allow-origin
  • Make CORS Request with Polymer iron-ajax and Node.js
  • How do CORS and Access-Control-Allow-Headers work?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Pure JavaScript equivalent of jQuery’s $.ready() – how to call a function when the page/DOM is ready for it

Next Post:

How to fetch all Git branches

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error