0

我試圖讓Ajax調用如下:AjaxCall的jQuery的

$.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)

+0

你不需要http:// localhost:8080 /,你應該只需要/ projects/1爲你的url – Keith

回答

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

如果沒有按」 t工作,那麼這應該工作:

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

第二個錯誤:未捕獲TypeError:無法讀取屬性'setRequestHeader'underi at beforeSend' –