我正在开发一个D3-grunt-cli应用程序,其中在向Fuseki服务器发送发布请求时遇到了CORS问题。
let arrayOfNumbers = [String]()
arrayOfNumbers.append("5555555544")
arrayOfNumbers.append("11111111111")
request.httpBody = getPostData(params: ["contactsList": arrayOfNumbers])
以上是我尝试提出请求的代码。仅当我在浏览器扩展程序中启用了CORS插件时,此方法才有效。
我还尝试通过对gruntfile.js中间件进行更改来包括访问权限。但这没有帮助。从中几乎可以肯定,这是服务器端的问题。
我的家属如下所示:
function saveToFusekiFunc() {
document.getElementById('fileid').click();
document.getElementById('fileid').value = null;
d3.select("#fileid").on("change", function() {
var contents;
var file = d3.select("#fileid").property("files")[0];
console.log(file);
var reader = new FileReader();
reader.onload = function(e) {
contents = e.target.result;
console.log(contents);
let xhr = new XMLHttpRequest();
let url = "http://localhost:3030/Test/";
xhr.open(
"POST",
url ,
true
);
//xhr.setRequestHeader('Data-Type', 'jsonp');
xhr.setRequestHeader('Content-Type', 'text/turtle;charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:8000/');
xhr.setRequestHeader('Access-Control-Max-Age', '86400');
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(contents);
};
reader.readAsText(file);
})
}
已经尝试了在线找到的大多数解决方案,但是除了直接阻止浏览器中的CORS检查之外,其他任何方法都没有起作用。我正在尝试从'http://localhost:8000/'向Fuseki服务器'http://localhost:3030/'发出请求。
我得到的错误是:
"dependencies": {
"d3": "^3.5.6",
"grunt-cli": "^1.3.2",
"lodash": "^4.1.0"
}
请求标头:
还检查了似乎具有CORS设置的Fuseki配置的web.xml文件:
Access to XMLHttpRequest at 'http://localhost:3030/Test/' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
答案 0 :(得分:1)
CORS请求使用了Origin
标头,响应将是诸如Access-Control-Allow-Origin
之类的标头。
代码在请求中使用标头设置响应标头,并且没有“来源”。
答案 1 :(得分:0)
要使CORS正常工作,必须在目标服务器上启用它,因此在这种情况下,请在Fuseki服务器中启用它。来自Wikipedia doc on CORS:
请注意,在CORS架构中,Access-Control-Allow-Origin标头是由外部Web服务(service.example.com)而不是原始Web应用程序服务器(www.example.com)设置的。在这里,service.example.com使用CORS允许浏览器授权www.example.com向service.example.com发出请求。
这是一个要点,尽管警告合理,但我尚未在服务器上尝试过: https://gist.github.com/danja/e8ecbf7e51f7a2616122