【问题标题】:CORS - Ajax or XMLHttpRequest type GET with "Authorization" get error 307CORS - 带有“授权”的 Ajax 或 XMLHttpRequest 类型 GET 获取错误 307
【发布时间】:2018-04-10 03:14:50
【问题描述】:

我需要在标头中使用“授权”执行 CORS 请求类型 GET,但由于某种原因它不起作用...我收到 307 内部重定向错误“预检响应无效(重定向)”或者我得到了401 Unauthorized 如果使用 HTTPS。

我试过这个:

$.ajax({
     url: "http://exemple.com/api/ajax.php",
     type: "GET",
       withCredentials: true, 
       crossDomain: true,
       dataType: 'jsonp',
       beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer A5MjE2DA1LCJzaWduIjoiZGJYTExNjM==');},
       success: function() { 
       alert('Success!' + xhr.responseText);}
  });

还有这个:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://exemple.com/api/ajax.php", true);
xhr.setRequestHeader("Authorization", "Bearer A5MjE2DA1LCJzaWduIjoiZGJYTExNjM==");
xhr.onload = function () {
    console.log(xhr.responseText);
};
xhr.send();

得到错误 307 内部重定向错误“预检响应无效(重定向)”

然后在服务器端,("Access-Control-Allow-Origin: *"); 看起来没问题,那么有什么问题吗?如何做到这一点?

【问题讨论】:

    标签: javascript ajax xmlhttprequest cors authorization


    【解决方案1】:

    您的请求未通过 CORS 预检检查。使用 307 重定向,服务器不会响应 preflight OPTIONS 请求而是重定向。

    您需要配置服务器以正确实施 CORS。有很多图书馆可以做到这一点。但如果你知道怎么做,你可以手动完成。

    服务器需要响应 OPTIONS 动词并使用 CORS 标头进行回复。在预检中,allow-origin 必须是绝对的,并且不允许使用通配符。对于允许方法返回 GET。对于允许标头返回授权。如果您使用凭据 (cookie),请将 Allow-Credentials 设置为 True。

    您的预检标头应如下所示:

    Cross-Origin-Allow-Origin: http://example.com
    Cross-Origin-Allow-Methods: GET
    Cross-Origin-Allow-Headers: Authorization
    Cross-Origin-Allow-Credentials: True
    

    【讨论】:

    • 我的请求标头有问题,这个Accept:*/* 我需要发送Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 怎么做?
    【解决方案2】:

    我的标题是这样的:

    Cross-Origin-Allow-Origin: *
    Cross-Origin-Allow-Methods: GET
    Cross-Origin-Allow-Headers: Authorization
    Cross-Origin-Allow-Credentials: True
    

    我的标题看起来已经正确了...那么有什么问题?

    【讨论】:

      【解决方案3】:

      Cross-Origin-Allow-Credentials:真 避免 跨源允许源:*

      您必须提供确切的原产地

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-20
        • 2015-10-20
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        • 2013-01-21
        • 2017-10-26
        • 2014-12-25
        相关资源
        最近更新 更多