【问题标题】:jQuery ajax basic authentication is not workingjQuery ajax 基本身份验证不起作用
【发布时间】:2017-12-03 02:54:21
【问题描述】:

我正在尝试向一些基本的 http 认证 url 发出 jQuery AJAX 请求。 这是我的 jQuery 代码:

jQuery.ajax({
  url: "https://abc.com/houses/1/appliance_hints",
  method: 'GET',
  cache: false,
  crossDomain: true,
  beforeSend: function(xhr){
    xhr.setRequestHeader('Authorization', 'Basic Z3NsYWI6cGFzczFnczFhYg==');
  },
  success: function(result){
    alert(result);
  }
});

我在这里设置请求标头“授权”。但这是我在 FF 的请求标头中看到的内容

Host    <host>
User-Agent  Mozilla/5.0 (Ubuntu; X11; Linux x86_64; rv:8.0) Gecko/20100101 Firefox/8.0
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection  keep-alive
Origin  <origin>
Access-Control-Request-Me...    GET
Access-Control-Request-He...    authorization,x-requested-with

我做错了吗? 我在响应中收到状态代码 302。 是否有任何服务器端配置错误?

【问题讨论】:

    标签: javascript ajax jquery basic-authentication http-authentication


    【解决方案1】:

    我注意到您已将crossDomain: true 添加到您的$.ajax 呼叫中,所以我认为您正在尝试从远程域中获取某些内容?

    无论如何,您遇到的主要问题是您违反了Same origin policy

    如果您可以控制remote_url(在您的示例中为 abc.com),则可以将其设置为发送一些标头以允许这些调用。

    示例:

    Access-Control-Allow-Origin: http://permitted_domain.com
    

    php 示例:

    header('Access-Control-Allow-Origin: http://permitted_domain.com');
    // or to allow all
    header('Access-Control-Allow-Origin: *');
    

    【讨论】:

      【解决方案2】:
      var settings = {
        "async": true,
        "crossDomain": true,
        "url": "YOUGETURL",
        "method": "GET",
        "headers": {
          "authorization": "Basic Z3NsYWI6cGFzczFnczFhYg==",
          "cache-control": "no-cache"
      
        }
      }
      
      $.ajax(settings).done(function (response) {
        console.log(response);
      });
      

      【讨论】:

        猜你喜欢
        • 2014-09-06
        • 2016-10-06
        • 2016-01-01
        • 1970-01-01
        • 2014-01-22
        • 2016-01-11
        • 2014-12-31
        • 2016-11-17
        • 1970-01-01
        相关资源
        最近更新 更多