使用HTTP基本身份验证与Aj​​ax调用

Ste*_*Ste 9 authentication ajax jquery http http-headers

我需要联系服务器以使用HTTP服务.

尝试使用浏览器访问服务,使用https://example.com/service基本身份验证对话框.

更改URL以https://username:password@example.com/service轻松绕过它.

尝试使用Ajax做同样的事情总是导致401 Unauthorized:

$.ajax({
    url: 'https://username:password@example.com/service',
    // rest repeats
    type: "GET",
    async: true,
    success: function(text) { alert('success'); },
    error: function (text) { alert('error') },
    complete: function(text) { alert('complete'); }
});
Run Code Online (Sandbox Code Playgroud)
$.ajax({
    url: 'https://example.com/service',
    username: username,
    password: password,
    // snip repeat
});
Run Code Online (Sandbox Code Playgroud)
$.ajax({
    url: 'https://example.com/service',
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Basic "
            + btoa(username + ":" + password));
    },
    // snip repeat
});
Run Code Online (Sandbox Code Playgroud)

小智 8

我自己也在用类似的方案挣扎..诀窍是用什么来玩jsonp(呃):

$.ajax({
        url: "https://localhost:8443/v1/accounts",
        type: 'GET',
        dataType: 'jsonp',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Basic bHVpZ2lAZ21haWwuY29tOmFiYzEyMzQ1');
        }
    })
Run Code Online (Sandbox Code Playgroud)