使用DHIS 2 API与Jquery跨域问题

时间:2014-08-04 20:09:55

标签: javascript jquery ajax api cross-domain

我试图实现一个使用DHIS 2 API的javascript应用程序。我花了一整天的时间尝试使用Jquery进行身份验证。

API说(https://www.dhis2.org/doc/snapshot/en/user/html/ch32s02.html)您需要使用base 64身份验证。我试图在Jquery中实现它,但我遇到了跨域问题。我尝试使用DHIS 2演示(https://apps.dhis2.org/dev/)进行身份验证,但未成功。然后我在本地计算机上设置了一个本地副本,但我仍然运行同一个问题,因为DHIS 2在不同的端口上运行。

我已尝试过jsonp和CROS,但徒劳无功。

这是我到目前为止尝试的代码

$(function(){
  var base_url = "http://apps.dhis2.org/demo/";
  var login = 'dhis-web-commons-security/login.action?authOnly=true';
  var current_user_url = 'api/users.json';
  var params = {
       'j_username':'admin',
      'j_password':'district'
 };


 function base_64_auth(user,password) { 
      var tok = user + ':' + password;
      var hash = Base64.encode(tok);
      return "Basic " + hash;
 }

 var auth = base_64_auth('admin','district');

 $.ajax({
      url : base_url+login,
     data : params,
     type : 'POST',
     dataType : 'text',
     crossDomain : true,
     xhrFields : {
          'withCredentials':true
     },
     beforeSend : function(req) {
          req.setRequestHeader('Authorization',auth);
     },
     success : function(data){
          console.log('authentification succeded');
          alert('success');
          //userInfo();
     },error : function(xhr,type,msg) {
          console.log(xhr.responseText);
          console.log(type);
          console.log(msg);
     }
 });

)};

我使用简单的库进行base64编码www.webtoolkit.info/javascript-base64.html#.U9_O2XVdWkA

检查控制台我看到了这个错误:

XMLHttpRequest无法加载http://apps.dhis2.org/demo/dhis-web-commons-security/login.action?authOnly=true。请求被重定向到'http://apps.dhis2.org/demo/dhis-web-commons/security/login.action?failed=true',对于需要预检的跨域请求,我们不允许这样做。

如果有人曾经使用过该API,我将非常感谢他的帮助,或者如果你知道其他任何方式(包括其他语言),我可能会与API交谈,我可以选择它。

非常感谢你。

6 个答案:

答案 0 :(得分:1)

浏览器通常会阻止跨域请求。我自己正在使用DHIS2 API作为小组项目的一部分,我们通过运行以下方法来解决这个问题:在chrome中禁用同源策略:

google-chrome --disable-web-security

请注意,您仍然需要对演示服务器的请求进行身份验证,并且此解决方案在任何方面都不理想。我猜测最好的方法是在本地部署服务器并将所有文件放在服务器上,以便请求发生在与服务器相同的域上。另请注意,在Chrome中禁用Web安全性时,最好使用其他浏览器来处理邮件,Facebook等。

答案 1 :(得分:1)

DHIS版本2.18有一个启用CORS的选项。应允许进行CORS访问的域可以在系统设置中列出 - >远程访问

https://www.dhis2.org/218

答案 2 :(得分:0)

在2.18版本中,DHIS 2增加了对CORS的支持,允许跨不同的来源/域共享资源。

您可以设置DHIS 2实例将接受来自应用程序>的请求的域名白名单。设置>访问。换句话说,您必须在DHIS 2内部定义您计划请求DHIS 2数据的域。因此,如果您计划在webportal.org上设置从DHIS 2检索数据的Web门户,则必须将webportal.org定义为列入白名单的CORS域。

Docs here

答案 3 :(得分:0)

尝试以下php代码:

$post_string_b64 = base64_encode("user:password");

$auth = 'Authorization: Basic '.$post_string_b64;

$ch = curl_init("dhis2server/api/dataSets?paging=false");

curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth));

curl_setopt($ch, CURLOPT_HEADER, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

$html = curl_exec($ch);

然后你会得到 json响应 ,你可以通过以下方式使其可读:

$pattern = '/\{(.+)\}/';

preg_match($pattern, $html, $matches);

$json = json_decode($matches[0], true);

代码应该是自我解释的,但可以随意询问不清楚的内容,

此致

答案 4 :(得分:0)

@Ajmal A. 我可以确认在系统设置 - >中编辑相应的CORS设置。访问 - > CORS白名单有效。我们使用的是DHIS2版本2.25。

CORS whitelist 我正在localhost:3000上正在处理我们的客户端应用程序,在白名单之后,我现在可以使用以下jQuery AJAX调用来获取数据。

var apiUrl = "https://<YOUR_URL>/api/<YOUR_RESOURCE>?format=json";
$.ajax({
    url: apiUrl,
    type: "GET",
    crossDomain: true,
    xhrFields : {
        'withCredentials':true
     },
    dataType : "json",
    username: "<YOUR_USERNAME>",
    password: "<YOUR_PASSWORD>"
})
  .done(function( json ) {
      console.log(json);
  })
  .fail(function( xhr, status, errorThrown ) {
    console.log( "AJAX request failed on " + apiUrl );
    console.log( "Error: " + errorThrown );
    console.log( "Status: " + status );
    console.dir( xhr );
  })
  .always(function( xhr, status ) {
    console.log( "AJAX request closed." );
  });

答案 5 :(得分:-1)

您无法从外部DHIS平台(即不同的域)访问。 DHIS不允许这样做。 我也花了两天时间。然后,DHIS志愿者告诉了我。