ajaxcalljquery

ajaxcalljquery,jquery,ajax,basic-authentication,Jquery,Ajax,Basic Authentication,我尝试进行如下Ajax调用: $.ajax({ type: "GET", dataType: "json", contentType: "application/json", username: "user", password: "admin", url: "http://localhost:8080/projects/1", xhrFields: { wi

我尝试进行如下Ajax调用:

$.ajax({ 
        type: "GET",
        dataType: "json",
        contentType: "application/json",
        username: "user",
        password: "admin",
        url: "http://localhost:8080/projects/1",
        xhrFields: {
            withCredentials: true
       },
        success: function(data){     
            console.log(data);
        }
    });
但我得到了以下错误:

Failed to load resource: the server responded with a status of 401 ()

我错过什么了吗?(端点上的身份验证是HTTPBasicAuthorization)

似乎需要这样做:

完整代码:

headers: {
    "Authorization": "Basic " + btoa(username + ":" + password)
  },
完整代码:

$.ajax({ 
        type: "GET",
        dataType: "json",
        contentType: "application/json",
        url: "http://localhost:8080/projects/1",
        headers: {
            "Authorization": "Basic " + btoa(username+ ":" + password)
        },
        success: function(data){     
            console.log(data);
        }
    });
如果这不起作用,那么这应该起作用:

 beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},

似乎你需要这样做:

完整代码:

headers: {
    "Authorization": "Basic " + btoa(username + ":" + password)
  },
完整代码:

$.ajax({ 
        type: "GET",
        dataType: "json",
        contentType: "application/json",
        url: "http://localhost:8080/projects/1",
        headers: {
            "Authorization": "Basic " + btoa(username+ ":" + password)
        },
        success: function(data){     
            console.log(data);
        }
    });
如果这不起作用,那么这应该起作用:

 beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},

您不需要,您应该只需要/projects/1作为您不需要的URL,您的URL只需要/projects/1。第二个错误:
uncaughttypeerror:无法读取beforeSend未定义的属性“setRequestHeader”
second-one错误:
uncaughttypeerror:无法读取beforeSend未定义的属性“setRequestHeader”