400 错误请求仅使用 AngularJs,适用于 jQuery

400 Bad Request only using AngularJs, works with jQuery

我在使用 AngularJs 进行特定 "PUT" Ajax 请求(RESTFul 服务)时遇到问题。

同一段代码适用于 jQuery 和普通 JavaScript。

$http({
    method: "PUT",
    url: "https://XXXXXXXXXXXXXX/api.php?rquest=updateUuid",
    headers: {
        "Content-type": "text/plain",
        Authorization: "Basic " + btoa(email + ":" + password)
    },
    data: {
        Email: email,
        Uuid: login_response.uuid
    }
}).success(function(response) {
    console.log(response);
});


jQuery.ajax({
    method: "PUT",
    url: "https://XXXXXXXXXXXXXX/api.php?rquest=updateUuid",
    headers: {
        "Content-type": "text/plain",
        Authorization: "Basic " + btoa(email + ":" + password)
    },
    data: {
        Email: email,
        Uuid: login_response.uuid
    }
}).done(function(response){
    console.log(response)
});

服务器正在响应 JSON object,但第一个代码 (AngularJs) 的工作方式似乎有点不同。 在我没有设置 Content-Type header 之前,我遇到了 CORS 问题(与 jQuery 一起工作,但 AngularJs 将 content-type 设置为 "application/json" 并导致错误)。

我得到了第一部分,将 content-type 设置为 text/plain,但现在我得到了 400 Bad Request Error(仅限 AngularJs)。我也尝试过使用拦截器删除 transformRequest,但没有用。

我使用AngularJs错了吗?因为我在想,unlinke jQuery,它在后台做额外的 "stuff",做一些额外的 header 或没有正确传递数据。

通常,当我没有将任何数据传递给 RESTful 服务时,我会收到该错误。

我正在学习AngularJs,所以我宁愿使用它而不是jQuery。 任何帮助将不胜感激。

非常感谢

我知道了,jQuery 自动将数据对象序列化为 application/x-www-form-urlencoded,AngularJs 不是...

工作代码:

$http({
    method: "PUT",
    url: "https://XXXXXXXXXXXXXX/api.php?rquest=updateUuid",
    headers: {
        Accept: "*/*",
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: "Basic " + btoa(email + ":" + password)
    },
    data: jQuery.param({
        Email: email,
        Uuid: login_response.uuid
    })
})

无论如何,这看起来不太好,但它至少在工作.. 任何人都知道一种更好的方法来让 AngularJs 以 x-www-form-urlencoded 形式发送序列化数据?