阿贾克斯授权请求头连连失败 [英] Ajax Authorization Request headers fails again and again

查看:199
本文介绍了阿贾克斯授权请求头连连失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个消费者对一个白手起家的API,并具有设置在 Authorization头严重的困难。我使用的JQuery的Ajax请求,但在beforeSend都不能正常工作(使用提琴手以检查请求)

I'm working on a consumer for a self-made API and having serious difficulties with setting the Authorization header. I am using JQuery for the Ajax requests, but the 'beforeSend' does not work at all (using fiddler to examine the requests)

这是我beforeSend code:

This is my beforeSend code:

    $.ajax({
     type: "GET",
     url: url+"/Projects",
     contentType: "application/json; charset=utf-8",
     beforeSend: function (req) {
        req.setRequestHeader("Authorization", AuthBuilder(username, password));
     },
     success: function (result) {
        alert("success");
     },
     error: function (xhr, ajaxOptions, thrownError) {
        alert("fail");
     }
 });

那么,如果失败了你会怎么做?回到旧的方式来发送Ajax请求......嗯,这也不行......

Well if that fails what do you do? Go back to the old way for sending ajax requests... well this doesn't work either...

这是我的正常code:

This is my regular code:

function GET(address, callback, error) {
Request = getXMLHttpObject();
Request.open("GET", url + address, true);

var base64 = Base64.encode(username + ":" + password);
alert(base64);
Request.setRequestHeader("Authorization", "Basic " + base64);

Request.send();
Request.onreadystatechange = function () {
    //alert(Request.readyState+" code "+Request.status);
    if (Request.readyState == 4 && Request.status == 200) {
        callback(jQuery.parseJSON(Request.responseText));
    } else if (Request.readyState == 4 && Request.status >= 400) {
        error(Request.status, Request.statusText);
    }
} 
}

不介意的事实,我不要求对JSON特别是因为该服务通过返回的JSON 默认

在附加信息:

  • 产地没有关系,该服务允许所有起源(已通过测试并确认)
  • 授权作品时,通过在头设置(在其他客户端测试)
  • 授权头只是不发
  • AuthBuilder(用户名,密码))给出了基本认证头内容的正确格式
  • 的getXMLHttpObject()只是一些复制粘贴code和之前
  • 工作

什么想法?

推荐答案

嗯,我发现了什么问题。自制服务发送这回客户端作为一个全球性的标题:访问控制 - 允许 - 头,在这唯一的内容类型

Well I found out what the problem was. The self-made service sent this back to the client as a global header : "Access-Control-Allow-Headers" with only "Content-Type" in it.

这样,我们不使用用户代理(浏览器)客户端忽略了这些头和刚发的头呢。但是,浏览器试图优化的要求,并说:这会不会接受Authorization头所以在发送前我就砍了。这种方式是封装更小,该服务将不会允许它反正(虽然它...)

This way our clients not using an User Agent (browser) ignored these headers and just sent the header anyway. But the browser tried to optimize the request and said "It won't accept the Authorization header so I'll just cut it before sending." this way is the package is smaller and the service won't allow it anyway (although it did...)

因此​​,只要加入授权的访问控制允许头的服务的一部分做我的JavaScript / JQuery的/ Ajax请求发送的请求头为正常!

So just adding "Authorization" to the Access Control Allow Headers part of the service made my Javascript/JQuery/Ajax requests send the request header as normal!

这篇关于阿贾克斯授权请求头连连失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆