Jquery ajax相当于Angular中的withcredentials

时间:2015-12-02 11:37:53

标签: jquery angularjs ajax couchdb

我目前正在使用angular来向我的localhost CouchDB发送HTTP GET请求。我是通过AngularJS完成的:

var req =
{
    method: 'POST',
    url: BASEURL+'_session',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: 'name=' + APIKEY + '&password=' + APIPASSWORD,
    withCredentials: true
}
$http(req).then
            (function(result) {console.log(result.data);},
             function(error) {console.log(error)});

并且只是尝试使用AJAX(我是绝对的初学者)来做同样的事情。 我似乎无法在ajax中使用相同版本的“withcredentials”....任何人都可以帮忙吗?无论如何,我都获得了401 Unauthorized -

Failed to load resource: the server responded with a status of 401 (Unauthorized)

这是我到目前为止所做的:

-edit-

var jqxhr = $.ajax({
     url: BASEURL+'_session',
     headers: {"Content-Type": "application/x-www-form-urlencoded"},
     data: 'name=' + APIKEY + '&password=' + APIPASSWORD,
     type: "POST",
     success: function(response)
     {
         alert('Success!' + response);
         var jqxhr2 = $.ajax({
         url: BASEURL+DATABASE+'/users',
         type: "GET",
         success: function(response)
         {
             alert('Success!' + response);

         }
        });
     }
    });

1 个答案:

答案 0 :(得分:0)

您可以将withCredentials设置为true以获取跨域请求,如下所示:

$.ajax({
       url: BASEURL+DATABASE+'/'+'users',
       contentType: "application/x-www-form-urlencoded",
       data: 'name=' + APIKEY + '&password=' + APIPASSWORD,
       type: "POST",
       xhrFields: { withCredentials: true },
       success: function() {
                 alert('Success!' + authHeader); 
                } 
     });