AjaxCall Jquery

时间:2017-09-07 15:31:37

标签: jquery ajax basic-authentication http-basic-authentication

我正在尝试按如下方式进行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)

1 个答案:

答案 0 :(得分:0)

似乎你需要这样做:

完整代码:

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