2016-06-21 43 views
0

未能提交用戶名/密碼使用JavaScript,但與一般的網絡瀏覽器,而在地址欄中使用直接URL它通過在彈出菜單中手動插入用戶名密碼。JavaScript - 未能提交用戶名,密碼

如何解決?從服務器

<script> 
function make_base_auth(user,password) { 
    var tok = user + ':' + password; 
    var hash = btoa(tok); 
    return "Basic " + hash; 
} // ends 

$(document).ready(function() { 
    $.ajax({ 
    type: "GET", 
    url: "http://www.example.be/a/b/c?id=9990", 
    dataType: 'xml', 
    async: false, 
    data: '', 
    beforeSend: function(xhr) 
    { 
     xhr.setRequestHeader('Authorization', make_base_auth("user1", "1234")); 
    }, 
    success: function (data, textStatus, jqXHR){ 
     console.log(data, textStatus, jqXHR); 
    } 
    }); 
}); 
</script> 

錯誤:

enter image description here

+0

你甚至使GET請求?還是在預檢OPTIONS請求時失敗? – Quentin

+0

我總是得到1)「預檢的響應具有無效的HTTP狀態代碼401」2)響應頭說:訪問控制 - 允許 - 方法:GET,POST,DELETE,PUT 2)請求頭說:訪問控制請求-Method:GET – YumYumYum

+0

因此,服務器未配置爲允許您創建跨源AJAX請求。您需要更改服務器,以便它允許您提出請求。 – Quentin

回答

0

提供標題:授權,緩存控制在標題:

var settings = { 
    "async": true, 
    "crossDomain": true, 
    "url": "http://www.example.be/a/b/c?id=9990", 
    "method": "GET", 
    "headers": { 
    "authorization": make_base_auth(user,password), 
    "cache-control": "no-cache" 
    } 
} 

function make_base_auth(user,password) { 
    var tok = user + ':' + password; 
    var hash = btoa(tok); 
    return "Basic " + hash; 
} // ends 


$.ajax(settings).done(function (response) { 
    console.log(response); 
}); 
+0

先生,我得到「預檢的響應具有無效的HTTP狀態代碼401」,仍然無法像以前那樣工作。 – YumYumYum

+0

OP已經將授權放入標題中,它只是使用不太好的語法。爲什麼要添加緩存控制標題幫助? – Quentin