gpt4 book ai didi

javascript - 在 XMLHttpRequest 中设置授权 header 更改 HTTP 动词

转载 作者:太空狗 更新时间:2023-10-29 13:11:49 26 4
gpt4 key购买 nike

今天我发现了 XMLHttpRequest 的一个奇怪行为。当我调用 GET 服务时,我发现如果我不设置 Authorization header ,来自 firefox 的请求是相同的。但是如果我添加“Authorization” header ,firefox 首先发送一个带有“OPTIONS”的请求,然后它发送一个“GET”请求。

我知道动词“OPTIONS”必须在服务器端处理,但我只是想知道为什么 XMLHttpRequest 会这样。虽然是跨域请求,但为什么浏览器先发送“OPTIONS”请求。为什么添加“授权” header 会改变行为。

这是我的 Javascript 代码和 Fidler Inspector 报告。

    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);
}

以及带有授权 header 的 fiddler 响应

enter image description here

enter image description here

但是当我不添加 Authorization 头时,浏览器直接发送 GET 请求,没有 OPTIONS 请求。

enter image description here

最佳答案

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.

因此在您的情况下,设置 Authorization header 会导致请求被预检,因此 OPTIONS 请求。

More info here

Spec on Cross-Origin Request with Preflight

关于javascript - 在 XMLHttpRequest 中设置授权 header 更改 HTTP 动词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22410925/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com