【问题标题】:Can't set a header using Cors and Ajax无法使用 Cors 和 Ajax 设置标题
【发布时间】:2014-07-03 02:52:03
【问题描述】:

您好,我正在尝试使用 Basic Auth 进行 http 请求,但我无法设置标头授权,并且它在服务器中是允许的。

阿贾克斯:

  $.ajax({  


        xhrFields: {  withCredentials: true  },
        beforeSend: function(xhr){xhr.setRequestHeader('authorization', 'Basic cmFmmFuQHBoaWlubm92YXRpb25zLmNv=');},
        url : 'http://www.vozi.dev.br/api/audio',           
        type: 'POST',
        data:  JSON.stringify(sender),
        dataType: 'json',
        contentType: 'application/json',
        success : function(data, textStatus, jqXHR) {   
                    //do something


        }

    });

Http 请求头:

Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,pt;q=0.6
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:www.vozi.dev.br
Origin:http://localhost:8080
Referer:http://localhost:8080/act_text.jsp
User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36

Http 响应头:

Access-Control-Allow-Headers:accept, authorization, content-type
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:*
cache-control:no-cache
Connection:Keep-Alive
Content-Type:text/html; charset=UTF-8
Date:Wed, 14 May 2014 20:15:53 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.6 (Ubuntu)
Set-Cookie:PHPSESSID=k6gg748e47b2fv67; path=/
Transfer-Encoding:chunked
www-authenticate:Basic realm="Secured Area"
x-debug-token:5373cef9430fe
X-Powered-By:PHP/5.5.3-1ubuntu2

错误:

OPTIONS http://www.vozi.dev.br/api/audio 401 (A Token was not found in the   SecurityContext.) jquery.js:8706
OPTIONS http://www.vozi.dev.br/api/audio Invalid HTTP status code 401 jquery.js:8706
XMLHttpRequest cannot load http://www.vozi.dev.br/api/audio. Invalid HTTP status code 401 

【问题讨论】:

    标签: ajax http-headers cors basic-authentication


    【解决方案1】:

    我假设您在 IE10 或 IE11 上遇到此问题,这不是 Chrome 的问题。 IE 不会发送带有 OPTIONS 请求的授权标头,因此在服务器端,如果您启用 Windows 集成身份验证,它会拒绝 OPTIONS 请求。

    我在另一个 stackoverflow 问题上发布了这个 workaround

    【讨论】:

    • 您好,感谢您的回复,我正在使用 Chome 和 Firefox,都出现了耻辱错误。
    • 它在 Chrome 中为我工作,不知道为什么它不适合你!!
    • 没有浏览器会与预检一起发送授权标头或任何其他自定义标头。这样做会违反 CORS 规范。你可以在这里阅读更多信息:w3.org/TR/cors/#preflight-request
    【解决方案2】:

    我发现我无法使用

      Access-Control-Allow-Origin:*
    

    如果我正在使用

      withCredentials: true
    

    需要设置原点。

    【讨论】:

    • 是的,我有一个选项请求的过滤器,它从请求中获取来源并添加到响应中,var origin = httpReq.Headers.Get("Origin"); httpRes.AddHeader(HttpHeaders.AllowOrigin, origin);
    猜你喜欢
    • 1970-01-01
    • 2019-05-07
    • 2018-02-26
    • 2020-12-24
    • 2021-07-18
    • 1970-01-01
    • 2018-09-06
    • 2015-05-21
    • 1970-01-01
    相关资源
    最近更新 更多