JQuery Ajax基本身份验证标头无法正常工作 [英] JQuery Ajax Basic Authentication Header doesn't work correctly
问题描述
我正在尝试在JQuery中的服务器上发出一个简单的GET请求。
I am trying to make a simple GET request on a Server in JQuery.
$.ajax({
headers: {
"Authorization": "Basic " + btoa("hello" + ":" + "world")
},
url: "http://hello.world?Id=1",
method: "GET",
success: function () {
},
}).then(function () {
});
问题在于,当发送请求时,身份验证标头未正确放入请求中:
The Problem is that when the Request gets sent, the Authentication Header is not put into the request correctly:
Host: hello.world
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Origin: null
Connection: keep-alive
Cache-Control: max-age=0
推荐答案
当向另一个源发送HTTP请求时,请求可以是简单或非简单。如果请求使用(或两者),则请求变得非简单
When sending an HTTP request to another origin, the request can be either "simple" or "non-simple". A request becomes non-simple if it uses either (or both)
- 除HEAD,GET或POST之外的HTTP动词;或者,
-
以外的请求标头
,Accept-Language
,内容语言
或内容类型
- An HTTP verb other than HEAD, GET, or POST; or,
- A request header other than
Accept
,Accept-Language
,Content-Language
, orContent-Type
由于您的请求设置了授权
标头,因此它非常简单。
Since your request sets the Authorization
header, it is non-simple.
请求非简单,浏览器首先使用OPTIONS方法发送预检请求。这是你在问题中看到的要求。 (请参阅预检请求中的HTML5 Rocks 和[我对 Access-Control-Allow-Origin标头如何工作?的回答)。预检不包括非简单标题,但在 Access-Control-Request-Headers
标题中列出它们。
When a request is non-simple, the browser first sends a preflight request using the OPTIONS method. That's the request you're seeing in your question. (See HTML5 Rocks on preflight requests and [my answer on How does Access-Control-Allow-Origin header work?). The preflight doesn't include the non-simple headers, but lists them in the Access-Control-Request-Headers
header.
如果服务器正确响应了预检,浏览器将然后发出实际请求。在这种情况下,浏览器正在从服务器中查找响应头 Access-Control-Allow-Headers:Authorization
,以指示非简单授权
标头可以在实际请求中发送。您的服务器必须在其响应中包含该标头。
If the server responds to the preflight correctly, the browser will then issue the real request. In this case, the browser is looking for the response header Access-Control-Allow-Headers: Authorization
from the server to indicate that the non-simple Authorization
header is okay to send in the actual request. Your server must include that header in its response.
这篇关于JQuery Ajax基本身份验证标头无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!