Can't set a header using Cors and Ajax

泪湿孤枕 提交于 2019-12-23 04:47:16

问题


Hello I am trying to do a http request with Basic Auth, but I can't set the header authorization and it is allowed in server.

Ajax :

  $.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 Request Header:

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 Response Header:

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

Error :

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 

回答1:


I assume your having this issue with IE10 or IE11, This is not an issue with Chrome. IE doesn't send authorization headers with OPTIONS request, so on server side if you enable Windows integrated authentication, it does reject the OPTIONS request.

I have this workaround posted on another stackoverflow question




回答2:


I find out that i can't use

  Access-Control-Allow-Origin:*

if I am using

  withCredentials: true

Is necessary to set the origin.



来源:https://stackoverflow.com/questions/23665003/cant-set-a-header-using-cors-and-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!