我正在編寫一個普通的JavaScrypt AJAX請求,從運行在localhost:8888
上的MAMP服務器連接到運行在localhost:7474
上的Neo4j數據庫。對本地主機上的Neo4j數據庫的AJAX請求沒有「訪問控制 - 允許 - 來源」錯誤
我收到此錯誤:
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.
繼答案類似的問題,我都試圖消除requeste頭,如...
// httpRequest.setRequestHeader("Content-type", "application/json")
...但是,這沒有區別。我也研究過CORS,卻沒有找到解決辦法。
我可以對我的JavaScript做些什麼改變才能使它起作用?有沒有辦法讓我告訴開發機器上的Neo4j數據庫服務器接受來自同一臺機器的請求?
我的源代碼:
<button type="button">AJAX Request</button>
<script type="text/javascript">
(function() {
var httpRequest
var restApiUrl = "http://neo4j:[email protected]: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>
編輯迴應@WilliamLyon
當我改變makeRequest
方法使用jQuery的$.ajax
方法(如下圖所示),我仍然得到同樣的錯誤,即使我使用contentType: "application/json"
或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)
}
})
}
嘗試向傳遞給'$ .ajax()'的對象添加'contentType:'application/json''。只有JSON請求被包裝在JSONP中,我認爲它需要被明確設置。 –
或'dataType:'json'' –
仍然沒有快樂。但是,我成功創建了一個裸機[Node.js應用程序](http://stackoverflow.com/q/32957497/1927589),它允許我隔離拋出錯誤的查詢,所以我有辦法前進。 –