XMLHttpRequest is unable to load due to a technical issue

Seeking help to resolve an issue we've encountered. Despite trying various solutions, we keep encountering the Access-Control-Allow-Origin error when attempting to access keen.

Error message: Failed to load resource: the server responded with a status of 404 (Not Found) admin:1 XMLHttpRequest cannot load /queries/. Response for preflight has invalid HTTP status code 404

Snippet from admin.js:

<script type="text/javascript>
    var client = new Keen({
    projectId: "id", // String (required always)
    writeKey: "key", // String (required for sending)
    readKey: "key",      // String (required for querying)

    // protocol: "https",         // String (optional: https | http | auto)
    // host: "api.keen.io/3.0",   // String (optional)
    requestType: "jsonp"       // String (optional: jsonp, xhr, beacon)
});
Keen.ready(function() {
    var metric = new Keen.Query("newBusiness", {
        analysisType: "count",
        timeframe: "this_1_month"
    });

    client.draw(metric, document.getElementById("newBusiness-count-chart"), {
        chartType: "metric",
        label: "Count of Businesses"
    });
});

List of headers and origins used:

app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'https://api.keen.io:443, fonts.googleapis.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Origin, X-Requested-With, Accept');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-withCredentials', true);
next();

});

Answer №1

Here are some solutions to address the issues in the configuration provided:

Let's modify the code as follows:
  
var client = new Keen({
  projectId: "your_project_id",
  writeKey: "your_write_key",
  readKey: "your_read_key",
  requestType: "jsonp"
});

Keen.ready(function() {
  var metric = new Keen.Query("count", {
    eventCollection: "newBusiness", // Please ensure this is the correct collection name
    timeframe: "this_1_month"
  });
  client.draw(metric, document.getElementById("newBusiness-count-chart"), {
    chartType: "metric",
    title: "Count of Businesses"
  });
});

Answer №2

The server is having an issue processing preflight requests with HTTP status code 404, indicating that it may not be handling OPTIONS requests correctly. Preflight requests are made by browsers to check if the server will accept the actual request being sent. For example, if you have a code like

GET http://another-server.com/blah
, the browser will first send an OPTIONS request to http://another-server.com/blah with specific header values before proceeding with the original GET request.

You can observe these OPTIONS requests in the Network section of Chrome/Firefox/IE dev-tools (F12), although they can sometimes be unpredictable. This could mean that the service is not configured to support CORS properly or there are coding issues present.

Answer №3

Here are some troubleshooting steps that couldn't be included in a comment.

This code snippet demonstrates a simple CORS request that results in a 404 error "resource not found." It then attempts a second CORS request with a preflight, which fails with the following error:

Cross-Origin Request Blocked: The Same Origin Policy prevents access to the remote resource at . To resolve this, either move the resource to the same domain or enable CORS.

The code includes setting a custom header in the second request, triggering the preflight. Additionally, a try-catch block is used to display the full error in the console (as Firefox typically shows only NS_ERROR_FAILURE).

This indicates a potential misconfiguration on the server side for preflighted CORS requests, specifically OPTIONS.

To see it in action, execute the code snippet below

var url = 'https://api.keen.io/3.0/projects/queries'; 
var xhr = new XMLHttpRequest();


try {
  xhr.open('GET', url, false );
  xhr.send();
}
catch(e){ }
dump('GET - no preflight');


try {
  xhr.open('GET', url, false );
  xhr.setRequestHeader('X-PREFLIGHT', 'forced');
  xhr.send();
 }
catch(e){ }
dump('GET - with preflight');


function dump(method) {
  window.stdout.innerHTML += (
    'METHOD = ' + method + '\n' +
    xhr.status + ':' + xhr.statusText + '\n' +
    xhr.getAllResponseHeaders() + '\n' +
    xhr.responseText + '\n\n'
  );
};
<xmp id="stdout"></xmp>

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

VueJS throws an error indicating that the object cannot be extended

I have encountered an issue while trying to update the promo object by adding a new field called colspan. Unfortunately, I am getting this error: uncaught (in promise) TypeError: Cannot add property colspan, object is not extensible at eval (eval at ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

A guide on crafting OR queries in Elasticsearch using Node.js

I currently have a document structured like this: Sample document, [ { "_index": "xpertdox", "_type": "disease", "_id": "Ectopic Heartbeat", "_score": 24.650267, "_source": { "category": "Condition", "name": "Ectopic ...

Executing a POST request with AJAX in jQuery to communicate across different domains and fetching XML data as

Is it possible to send an AJAX request using the POST method and receive XML as a response text? If so, please provide me with the steps to achieve this. For example: url : "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate" data ...

Overlap and cover additional elements within a DIV

I am looking to create a versatile function that can effortlessly overlay various elements such as selects, textfields, inputs, divs, tables, and more with a partially transparent div matching their exact height and width. I have managed to obtain the pos ...

Trouble connecting JavaScript to Node application for proper functionality

After setting up Node/Express/EJS, I am now trying to include js files, but my alert("working"); is not working as expected. Quite ironic, isn't it? The main objective is to load learnJs.js in the browser and trigger the alert so that I can confirm e ...

Error: HTML code being displayed instead of form value in Ajax request output

For the past couple of days, I've been struggling with an Ajax issue that I just can't seem to figure out. Despite looking for a solution online, nothing seems to work. Below is the code snippet that's causing me trouble: <!DOCTYPE html& ...

Exploring the parent scope in handlebars.js partials

Is there a way to access the parent scope from a partial using #each in Handlebars? Main template: (out of each = {{index}})<br> {{#each someItem}} (in each, but not on partial = {{../index}}) {{>part}} {{/each}} Partial: <div class="part ...

Unable to locate the inner text of a Div element using ElementRef in Angular 9

I'm facing an issue with my code where I am trying to find the innerText of a div and change it. However, when I click on the button to retrieve the innerText, it shows as undefined. Check out the demo here <p #dviInner> Start editing to se ...

Data in DynamoDB Local is deleted once the instance is shut down

My app is utilizing DynamoDB Local and I am facing an issue where it keeps deleting all the sample data each time I shut down the instance. This problem seems to be unique as I have not found any similar cases while searching for a solution. I typically ...

Unexpected behavior when using AutoComplete in Material UI

Currently, I am developing a small application using react-redux and material-ui. However, I have encountered an issue with the autocomplete field while implementing the onNewRequest property. Instead of triggering when I select an element from the list, i ...

Choose specific columns from distinct tables and arrange them accordingly

I am facing a challenge with my MySQL database as it contains multiple tables with similar columns, and I want to import this data into a Google spreadsheet. For instance: table1 has id, name, page, and other specific columns. table2 also includes id, n ...

How can I perform a string search that doesn't take into account accented characters

Looking for a way to treat accented characters as equivalent to their non-accented counterparts in my code. Here's what I have so far: var re = new RegExp(string, 'i'); if(target.search(re) == 0) { } Currently, the code ignores the charact ...

Accessing information via a PHP script with the help of AJAX and jQuery

In the process of developing a gallery feature that displays a full image in a tooltip when hovering over thumbnails, I encountered an issue where the full images extended beyond the viewfinder. To address this, I decided to adjust the tooltip position bas ...

A beginner's guide to integrating ng-class into a directive template using AngularJS

I have been attempting to achieve something similar to the following: template: "<div ng-if=\"successData\" ng-class=\"{ 'bounceInDown': successData == true,bounceInDown: successData == false}\" style=\"border-radius ...

Error: The socket.io client script cannot be found when using Express + socket.io

This situation is really getting to me... even though I have a functioning version of Express + Socket.io, I can't replicate it in a new project folder with standard NPM installs. Can someone please help me figure out what I'm doing wrong...? Her ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Guide on uploading files and data simultaneously by leveraging ajax, jquery, and spring mvc

How can I use ajax, query, and Spring MVC to upload data along with a file? Below is my modal pop-up, could someone help me with this? <!-- Modal --> <div id="fileUpload" class="modal fade" role="dialog"> <d ...

Transferring information from nodejs/express to frontend JavaScript

I am faced with a challenge regarding accessing the 'data' sent from my backend server in my frontend js. Can anyone guide me on how to achieve this? Express ... app.get("/", (req, res) => { res.render("home", {data} ); }); ... home.ejs ...

Redirecting with response headers in Next.js

Objective: The Goal: Clicking a button on a page should send a request to the controller. The controller will then set a cookie, and upon receiving the response, redirect the page to another page, such as the about page. Directly Calling API route from th ...