今天我发现了一个奇怪的行为
XMLHttpRequest.当我调用GET服务时,我发现如果我没有设置授权头,则firefox的请求是一样的.但是,如果我添加“授权”头Firefox,首先使用“OPTIONS”发送请求,然后发送“GET”请求.
@H_502_13@解决方法
我知道动词“OPTIONS”必须在服务器端处理,但我只是想知道为什么XMLHttpRequest的行为是这样的.虽然是跨域请求,为什么浏览器首先发送“OPTIONS”请求.为什么添加“Authorization”头会更改行为.
这是我的Javascript代码和Fidler检查器报告.
var xmlhttp = new XMLHttpRequest(); var url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; xmlhttp.open('GET',url,true); xmlhttp.setRequestHeader("Authorization","xxxxxxxxxxxxxxxxxxx"); xmlhttp.send(null); xmlhttp.onreadystatechange = function() { alert("OnReadystatechange + " + xmlhttp.readyState + " " + xmlhttp.status); if (xmlhttp.readyState == 4) { if ( xmlhttp.status == 200) { } else { } } else alert("Error ->" + xmlhttp.responseText); }
和授权标头的提示响应
但是当我不添加授权头部时,浏览器直接发送GET请求,没有OPTIONS请求.
HTTP OPTIONS请求在实际发送之前用于“预检”跨源GET请求.
Unlike simple requests,“preflighted” requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain,in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular,a request is
preflighted if:
- It uses methods other than GET,HEAD or POST. Also,if POST is used to send request data with a Content-Type other than
application/x-www-form-urlencoded,multipart/form-data,or
text/plain,e.g. if the POST request sends an XML payload to the
server using application/xml or text/xml,then the request is
preflighted.- It sets any header that is not considered simple. A header is said to be a simple header if the header field name is an ASCII case-insensitive match for Accept,Accept-Language,or Content-Language or if it is an ASCII case-insensitive match for Content-Type and the header field value media type (excluding parameters) is an ASCII case-insensitive match for application/x-www-form-urlencoded,multipart/form-data,or text/plain.
所以在你的情况下,设置授权头会导致请求被预检,因此是OPTIONS请求.