Issue-free AJAX call to Neo4j database on local server with no 'Access-Control-Allow-Origin' problem

I'm currently working on a basic JavaScript AJAX request to connect from a MAMP server running at localhost:8888 to a Neo4j database running on localhost:7474.

The issue I'm encountering is the following error message:

XMLHttpRequest cannot load http://localhost:7474/db/data/transaction/commit. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 401.

In an attempt to resolve this, I've tried removing certain headers from the request such as:

// httpRequest.setRequestHeader("Content-type", "application/json")

However, this doesn't seem to make any difference. I also explored CORS but couldn't find a solution there either.

What modifications can I make to my JavaScript code to address this issue? Is it possible for me to configure the Neo4j database server on my development machine to accept requests from the same machine?

Here's a snippet of my source code:

<button type="button">AJAX Request</button>

<script type="text/javascript">
(function() {
  var httpRequest
  var restApiUrl = "http://neo4j:1234@localhost:7474/db/data/transaction/commit"

  document.querySelector("button").onclick = function() {
    makeRequest(restApiUrl)
  }

  function makeRequest(url) {
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest = new XMLHttpRequest()
    } else if (window.ActiveXObject) { // IE
      try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP")
      } 
      catch (e) {
        try {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP")
        } 
        catch (e) {}
      }
    }

    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance')
      return false
    }

    var parameters = JSON.stringify({
  "statements" : [ {
    "statement" : "CREATE (n {props}) RETURN n",
    "parameters" : {
      "props" : {
        "name" : "My Node"
      }
    }
  } ]
})

    httpRequest.onreadystatechange = alertContents
    httpRequest.open('POST', url, true)
    httpRequest.setRequestHeader("Content-type", "application/json")
    httpRequest.setRequestHeader("Accept", "application/json; charset=UTF-8")
    httpRequest.send(parameters)
  }

  function alertContents() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {
        console.log(httpRequest.responseText)
      } else {
        alert('There was a problem with the request.')
      }
    }
  }
})()
</script>

EDIT in response to @WilliamLyon

Even when I switch the makeRequest method to use jQuery's $.ajax function (as demonstrated below), I still encounter the same error, even after specifying contentType: "application/json" or dataType: 'json'.

function makeRequest(url) {
  var data = JSON.stringify({
    "statements" : [ {
      "statement" : "CREATE (n {props}) RETURN n",
      "parameters" : {
        "props" : {
          "name" : "My Node"
        }
      }
    } ]
  })

  $.ajax({
    url : url
  , type: "POST"
  , data : data
  , contentType: "application/json"
  , dataType: "json"
  , success: function(data, textStatus, jqXHR) {
      console.log(data, textStatus)
    }
  , error: function (jqXHR, textStatus, errorThrown) {
      console.log(jqXHR, textStatus, errorThrown)
    }
  })
}

Answer №1

You are currently dealing with a CORS issue.

What is happening?
Your browser, by default, is not allowed to access resources from other domains through AJAX requests. This is a security measure put in place to protect the web.

Possible solution

Here is a potential solution that worked for me locally:

$.ajax({
    url : "http://localhost:7474/db/data/transaction/commit",
    type: "POST",
    dataType: "json",
    contentType : 'application/json',
    data : JSON.stringify({
      "statements" : [ {
        "statement" : "CREATE (n {props}) RETURN n",
        "parameters" : {
          "props" : {
            "name" : "My Node"
          }
        }
      } ]
    }),
    success: function(data, textStatus, jqXHR) {
      console.log(data, textStatus)
    },
    error: function (jqXHR, textStatus, errorThrown) {
      console.log(jqXHR, textStatus, errorThrown)
    }
});

Key points to note:

  • dataType - specifies acceptance of JSON as response
  • contentType - indicates the use of JSON in the request

I am running Neo4j 2.2.5 locally. This version includes "Access-Control-Allow-Origin" in the response header, which helps avoid any issues. You can inspect the response headers sent by your database using Chrome DevTools.

Example:

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

Note: Check the "Response headers" section.

Answer №2

The reason for the error is due to the difference in port numbers. Typically, making cross-domain Ajax calls is not possible if the server does not allow it. However, there are methods to work around this limitation. Options include utilizing CORS or JSONP.

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

What is the best way to adjust a map to completely fill the screen?

I am experiencing an issue with my Openlayer map not fitting to full screen automatically. Despite trying various settings, I am unable to resolve this issue. Can anyone suggest what might be causing this problem? Thank you in advance https://i.stack.imgu ...

Discover the best practices for utilizing CSS selectors reliably in puppeteer

For a project, I am currently working on customizing a puppeteer script that is able to play a song from Soundcloud and record it. The main goal is to utilize a CSS selector to display the duration of the song as well. I am encountering difficulties with g ...

store user settings in local storage

After writing some code with a link that toggles text visibility upon click, I now want to incorporate saving this state in web storage so that it persists upon page reload. As a beginner in JavaScript and HTML, this task has proven challenging for me. Th ...

Emphasize SELENIDE rows

My goal is to achieve the following: @Test public void tableTest() { getDriver().get(BASE_URL + "tabulka.php"); List<WebElement> rows = getDriver().findElements(By.xpath("//table//tbody//tr")); for (We ...

Parsing JSON or eliminating double quotation marks in data acquired from a model or database within the Rails framework

foo.html.erb <script type="text/javascript"> var all_user_data = <%= @user.all_user_bar_chart.to_json.html_safe) %>; </script> abc.js $(function () { if ($("#foo").length > 0){ var user_charts = new Highcharts.Chart({ ...

Having trouble getting collision events to trigger in ThreeJS when using the PhysiJS physics engine?

When an object falls and collides with the ground, an alert box should pop up displaying the message "Box just hit the ground". However, there seems to be an issue as the alert box is not being created upon collision. Additionally, no relevant JavaScript ...

Maintain the webpage content even after submitting a form with a file attachment on the same page

I am in the process of creating a secure webpage exclusively for our members. This page will allow members to access their personal data stored in the database and upload files as needed. One concern I have is how to return to the member page with all the ...

Iterate through an Array of Objects and exhibit a single object property in HTML one at a time by utilizing Javascript

I am working with an array of objects that contain two properties: "quote" and "author". I have a container div where I want the quotes to be displayed one by one at an interval of every 2 seconds. Currently, it is showing one letter at a time instead of d ...

Is there a method to retrieve all Class elements without using a for-loop?

I am trying to retrieve all elements with a specific class using document.getElementsByClassName(); <body> <div class="circle" id="red"></div> <div class="circle" id="blue"></div> <div class="circle" id="yell ...

Is it possible to retrieve the width value when using layout=fill in next/image?

<Image alt="image_example" src="/image_example.png" layout="fill" objectFit="none" /> <Test width={?} height={?}/> I developed a straightforward component using next/image. I am interest ...

Using Javascript Reduce to Manipulate Objects

Here is the data I am working with: let info = [ {id: 1, name: "John Doe", type: "A", amount: 100}, {id: 2, name: "Jane Smith", type: "B", amount: 150}, {id: 3, name: "Alice Johnson" ...

Commitment of service within AngularJS controller using the "as" syntax

I'm experiencing an issue with the code snippet below. I prefer using the controller as syntax and assigning data to 'this' instead of $scope. The problem is that in this scenario, when using $scope.user everything works fine, but when tryin ...

Component's state not reflecting changes after dispatching actions in Redux, though the changes are visible in the Redux DevTools

When a menu item is clicked, I execute the following code: import React, { Component } from 'react'; import 'react-dropdown-tree-select/dist/styles.css'; import { connect } from 'react-redux'; import '../../../css/tree.c ...

Creating a versatile TailwindCSS grid that can adjust to varying numbers of grid columns

I am currently working with Vue3 and TailwindCSS, attempting to create a grid using a dynamic grid-cols-{n} class. While I am aware that TailwindCSS typically supports up to 12 columns by default, the challenge arises when the number of columns needed is e ...

Finding and merging duplicate values within a Javascript array

I am working with a dynamically generated array that looks like this: var myArray = ("0% { left:74px; top:202px; }" , "44% { left:427px; top:122px; }", "0% { font-size:11px; }", "55% { font-size:49px; }" ); Within the array, there are 2 entries that ha ...

Having difficulty applying parseFloat directly following a JSON Stringify operation

There's a specific line of code I'm working with that reads -- let longitude = JSON.stringify(place.lon); After calling alert(longitude), I receive the output "44.54321". However, my intention is to retrieve just the number itself, so I attempt ...

NgMap Angular Pins

While working on implementing Ng-Map for Angular in my application, I encountered an issue. I am retrieving entries from the database and attempting to drop markers on the map. However, even though I have 40 entries, only the first 11 are showing up as m ...

What are the steps to deploy a React, Next.js, and Express.js application on Netlify?

I am currently in the process of deploying my application to Netlify, featuring a combination of React, Next.js, and Express.js. While there are no errors showing up in the Netlify console, unfortunately, the site is not live as expected. https://i.stack ...

How can elements with class prefix names be retrieved in IE Browser Helper Object using c#?

I've been developing an IE Plugin using BHO and I need to access an element based on its class prefix in C#. In JavaScript and jQuery, I was able to accomplish this with the following code: var myClass = $('[class^="ii gt"]'); and var myC ...

React.js encountered an error: Objects cannot be used as a React child (found: object containing keys {type, data})

My current project involves displaying MySQL data in a table using Node.js and React.js. However, I keep encountering the following error: Error: Objects are not valid as a React child (found: object with keys {type, data}). If you meant to render a colle ...