跨域ajax请求基本身份验证

mik*_*e44 10 javascript asp.net ajax jquery web-services

我正在制作跨域ajax请求来获取一些数据.REST服务具有Basic authentication(设置IIS).

$.ajax({
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            dataType: "jsonp",
            contentType: "application/javascript",
            data: myData,
            async: false,
            crossDomain: true,
            url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData",
            success: function (jsonData) {
                console.log(jsonData);
            },
            error: function (request, textStatus, errorThrown) {
                console.log(request.responseText);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
Run Code Online (Sandbox Code Playgroud)

当我发出此请求时,它会提示我输入凭据,我必须手动输入凭据才能获得响应.我们可以通过请求本身发送这些凭据吗?

Cha*_*mal 5

传递用户名和密码,如下面的代码,

$.ajax({
    type: "GET",
    xhrFields: {
        withCredentials: true
    },
    dataType: "jsonp",
    contentType: "application/javascript",
    data: myData,
    async: false,
    crossDomain: true,
    url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData",
    success: function (jsonData) {
        console.log(jsonData);
    },
    error: function (request, textStatus, errorThrown) {
        console.log(request.responseText);
        console.log(textStatus);
        console.log(errorThrown);
    }
    username: username,
    password: password,
});
Run Code Online (Sandbox Code Playgroud)


Adi*_*ith 5

$.ajax({  
    url: 'yoururl',
    username : username,
    password :password,
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    dataType: "text",
    xhrFields: 
    {
        withCredentials: true
    },
    beforeSend: function (xhr) { 
        xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));             
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 我对这个答案并不感到兴奋,原因如下:它是多余的(问题在大约半年前得到回答)并且它是多余的(jQuery 为您处理身份验证的东西,AFAICT)。如果我对后者有误,请编辑答案,我将删除此评论。 (2认同)