CORS error: The 'Access-Control-Allow-Origin' header is missing

I have a website that is being accessed through multiple domain names.

Let's say the main hosted website is example.com and the forwarded domain names are example-x.com, example-y.com, example-z.com

When visitors access the forwarded domains, there are cross-domain requests made back to the main site, example.com.

Currently, I am encountering an error while making AJAX GET requests to JSON files:

The requested resource does not have the 'Access-Control-Allow-Origin' header. This means that the origin '' is not allowed access.

Even though the preflight OPTIONS request returns a status of 200 and the subsequent GET method also returns a status of 200.

OPTIONS;

https://i.sstatic.net/eNY9r.png

GET https://i.sstatic.net/A5D5f.png

I have added the following CORS headers in the host's .htaccess file;

# <IfModule mod_headers.c>
   SetEnvIfNoCase Origin "https?://(www\.)?(example-x\.com|example-y\.com|example-z\.com)(:\d+)?$" ACAO=$0
   Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO
   Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
  Header set Access-Control-Allow-Headers "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range"
Header set Access-Control-Allow-Credentials true
# </IfModule>

And I'm using the following AJAX request for making GET calls;

var createCORSRequest = function(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) { 
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest !== "undefined") { 
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else { 
        xhr = null;
    }
    return xhr;
}; 

var url = 'http://example.com/data.json'; 
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.setRequestHeader('Accept', 'application/json, text/javascript');  
xhr.onload = function() { console.log('success');}; 
xhr.onerror = function() { console.log('error'); }; 
xhr.send();

EDIT

After removing

setRequestHeader("Content-Type", "application/json; charset=UTF-8")
from the AJAX request, the preflight requirement was eliminated. However, the CORS error still persists. The screenshot below displays the request/response of the GET method. My assumption is that the correct .htaccess headers have not been set on the RequestURL - http://example.com/cms/wp-content/uploads/2017/04/preloader_data.json

GET - WITHOUT OPTIONS PREFLIGHT https://i.sstatic.net/9TO1S.jpg

Answer №1

When trying to retrieve a JSON using a GET request, it is important that it is treated as a simple request, eliminating the need for a preflight request.

According to the requirements outlined in MDN, any setting of Content-Type other than

application/x-www-form-urlencoded
, multipart/form-data, or text/plain will trigger the need for a preflighted request.

Referring to the RFC on content-type, it specifies a "SHOULD" for "a message containing a payload body," which your GET request does not have. Therefore, it is advised to remove that header from your ajax call.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identifying the Ajax request URL

I am working on a project where I have an HTML document that retrieves content from a PHP file using an AJAX call. The key portion of my code can be seen below: default.html : /*more code above*/ var PHP_URL = "content.php"; var Content = document.getEle ...

Generating fresh Mongodb Records versus Appending to a Document's Collection

A device that records temperature data every second feeds into a real-time chart using Meteor.js to display the average temperature over the past 5 seconds. Should each temperature reading be saved as a separate MongoDB document, or should new readings be ...

Check the validity of multiple selection groups using JavaScript

Here is the link to my JS Fiddle: http://jsfiddle.net/m4tyC/ I am working with multiple select tags and need to validate them upon submission. For example, at least one of size1, color1, or Qty1 must be selected in the first group. If one item is selected ...

Starting an AngularJS module without an HTML page may seem like a daunting task,

I am currently developing a browser extension project using AngularJS. Within the background.js file (which contains the code that runs in the background), I have created a module with a run block. var myExtensionModule = angular.module('myExtension ...

ReactJS is in need of extracting certain values from a promise

Within my Firebase database, I have organized data into two Documents: "users" and "posts". Each post in the "posts" collection is linked to a specific user using their unique id from the "users" collection. My goal is to retrieve user data associated wi ...

Web Browser cross-origin AJAX requests

Recently, I developed an Internet Explorer extension that injects a script every time a page is accessed. The purpose of this script is to send an AJAX request to my localhost. However, I have encountered a roadblock where the request only works if it&apos ...

Using CSS files from node modules within a meteor application

Incorporating the froala editor into my Meteor and React project has presented a unique challenge. The editor mandates the importation of CSS files, as outlined in the documentation here: . However, upon importing a specific CSS file using the command belo ...

Grab a parameter from the URL and insert it into an element before smoothly scrolling down to that

On a button, I have a URL that looks like this: www.mywebsite.com/infopage?scrollTo=section-header&#tab3 After clicking the button, it takes me to the URL above and opens up the tab labeled tab3, just as expected. However, I would like it to direct m ...

Changing the custom route in React Router to utilize a render prop instead of the component prop

I'm currently working on a React app that incorporates React Router. I've been encountering a bug in my code stemming from my custom ProtectedRoute component: const ProtectedRoute = ({ component, ...args }) => ( <Route component={with ...

Issues with BrowserHistory in react-router causing malfunction

My URL structure is currently storing history in hash syntax like this: Ex: http://localhost:3000/#/work?_k=otstr8 I am attempting to switch to using browserHistory from react-router so that it displays as: http://localhost:3000/#/work Below is my r ...

What steps should I take to develop a one-page ASP.NET web application that sends data to a database?

So, I've been working with ASP.NET as a web developer for quite some time now, but I usually start with a prepackaged ASP.NET MVC site and extend it from there. However, at the moment, all I need to do is create a single-page ASP.NET page that submits ...

Issue: Unable to extract the 'title' property from '(0 , react__WEBPACK_IMPORTED_MODULE_1__.useContext)(...)' as it is not defined (Next.js Chat App)

Currently facing an issue with the error message "Cannot destructure property 'title' of '(0 , react__WEBPACK_IMPORTED_MODULE_1__.useContext)(...)' as it is undefined" while developing a chat application using Next.js and Solidity. Desp ...

Setting up the JSON reply

When creating a schema using Joi and expecting a JSON response that matches the schema upon POSTing, an issue arises. The dilemma is having to include a parent element (in this case "data:") in the JSON response, although ideally the schema's attribut ...

Model in Sequelize does not get updated

I have a basic user model with two simple relationships: export const Password = sequelize.define("password", { hash: { type: DataTypes.STRING, allowNull: false, }, salt: { type: DataTypes.STRING, allow ...

Having trouble sending variables with Jquery Ajax GET method

The URL provided below is functioning correctly: index.php?page=search_result&maker=Any I am attempting to navigate to this URL from another page using a Jquery Ajax function. Below is my Ajax call: $(function(){ $(".by_maker").on('click&a ...

Customized pop-up alerts on web browsers

Is there a library available that provides notification features similar to those seen on Web Slack and Web Skype, allowing users to receive notifications even when they are not currently on the site page? https://i.sstatic.net/wANRg.png Thank you, and I ...

Identify specific elements using CSS to easily target them with JavaScript later on

Currently, I am utilizing CSS selectors to target specific elements and now I want to be able to identify those elements using javascript. My approach involves setting the color of these elements in css and then retrieving them based on their color. Howeve ...

Tips on waiting for an event to be processed during a Protractor end-to-end test

I have a straightforward AngularJs 1.4.8 Front-End: https://i.stack.imgur.com/2H3In.png After filling out the form and clicking the OK button, a new person is added to the table. The form resides in the addingPersonController, while the table is control ...

Switch positions of two objects in JavaScript

Check out the code snippet below: MyObject.prototype.doIt = function() { let a = this.obj1; let b = this.obj2; } I need to find a way to switch the values of this.obj1 and this.obj2, making obj1 take on the value of obj2 and vice versa. Pleas ...

Using AJAX to fetch information from a different page following a post request

Although this may seem simple, I am struggling with finding the correct jQuery equivalent to my existing DOM code. Despite going through various questions on Stack Overflow, I can't find a solution. Here is the script I currently have: function sear ...