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)
}
})
}