从 JavaScript 向 SDC HTTP 服务器 url 发布数据显示 CORS 问题

Posting data to SDC HTTP server url from JavaScript shows CORS issue

我正在使用 Streamsets 管道从浏览器流式传输数据。因此,为此,我创建了一个具有 HTTP 服务器来源的管道到来自浏览器 Javascript 的 post 数据,并尝试使用 REST 客户端写入 URL,并且写入成功。响应 Headers 已在 SDC.properties 文件中设置。

http.access.control.allow.origin=*
http.access.control.allow.headers=origin, content-type, accept, authorization, x-requested-by, x-ss-user-auth-token, x-ss-rest-call
http.access.control.allow.methods=GET, POST, PUT, DELETE, OPTIONS, HEAD

但是当我尝试使用 XMLHTTPRequest 从 JavaScript 写入一些数据时,它会为 pre-flight 请求抛出错误。下面是 JavaScript 代码:

  var http = new XMLHttpRequest();
  var value = '{ "prop1": "value 2", "prop2": "value 2" }';
  var url ='http://13.68.93.97:8100/'
  var async = true
 if ('withCredentials' in http) {
    http.open('OPTIONS', url, async);
} else if (typeof XDomainRequest != "undefined") {
    http = new XDomainRequest(); //for IE
    http.open('OPTIONS', url);
} else {
    http.open('OPTIONS', url, async);
}
    http.open('POST', url, true);
    http.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    http.setRequestHeader('X-SDC-APPLICATION-ID', 'testApp1');
http.setRequestHeader("Access-Control-Allow-Origin", "*");
http.setRequestHeader('Access-Control-Allow-Methods', "POST, OPTIONS, GET");
http.setRequestHeader('Access-Control-Allow-Credentials', "true");
http.setRequestHeader('Access-Control-Expose-Headers', "X-Region");
http.setRequestHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Accept-language");
http.withCredentials = true;
http.onreadystatechange = function () {
    if (http.readyState == 4 && http.status == 200) {
        console.log(http.responseText);
    }
}
http.send(value); 

以上代码执行抛出的错误:

XMLHttpRequest cannot load http://13.68.93.97:8100/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

任何帮助都会很有帮助。谢谢..!!

更新 - Data Collector 在 2017 年 3 月发布的 2.4.0.0 版中添加了 CORS 支持

StreamSets 数据收集器目前在 HTTP Server origin - those properties in the sdc.properties file are for the SDC web UI. I've filed a Jira, SDC-5298 中不支持 CORS,但我对您的用例很好奇。您只是使用浏览器进行实验,还是看到用户通过 JavaScript 向 SDC 发送数据的生产用例?

如果您有生产用例,请对该 Jira 发表评论,我们将研究如何将 CORS 添加到 HTTP 服务器源。

如果您只是想要一种轻松发送数据的方式,您有以下几种选择:

  1. 从命令行使用 curl:

    curl http://localhost:8000/ -H 'X-SDC-APPLICATION-ID: bob' -d '{"a":"b"}'
    
  2. 安装 Chrome 扩展,例如 CORS Toggle 以禁用 CORS 检查 Chrome.

  3. 使用 --disable-web-security 选项启动 Chrome。