2016-06-21 101 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