我将 Jetty 服务器配置为允许跨域 http 请求 (allowedOrigins = *),并允许使用其 CrossOriginFilter 进行跨域身份验证 (allowCredentials=true)。
无需身份验证的跨域 http 请求可以正常工作。现在,当涉及到需要身份验证的 http 调用时,使用 JQuery 就行不通了。我使用以下代码并遵循此示例:http://www.aswinanand.com/2009/01/http-basic-authentication-using-ajax/ http://www.aswinanand.com/2009/01/http-basic-authentication-using-ajax/
function login(username, password) {
$.ajax({
type: "GET",
contentType: "application/json",
dataType: "json",
url: url,
beforeSend: function(xhr) {
var base64 = Base64.encode(username + ":" + password);
xhr.setRequestHeader("Authorization", "Basic " + base64);
xhr.withCredentials = true;
},
error: function(data){
alert("error");
},
success: function(data){
alert("success");
}
});
在 HTTPFox 中,我看到对服务器的以下请求:
OPTIONS /login HTTP/1.1
...
Access-Control-Request-Method GET
Access-Control-Request-Headers authorization,content-type
服务器响应一个
HTTP/1.1 204 No Content
...
Allow OPTIONS,GET,HEAD
我还使用了下面的选项,这没有什么区别。
$.ajax({
...
username: username,
password: password,
...
}
错误函数总是触发。
有人知道问题可能是什么吗?