400 Bad Request仅使用AngularJs,适用于jQuery

时间:2015-02-05 14:14:15

标签: javascript jquery ajax angularjs rest

我在使用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对象进行响应,但第一个代码(AngularJs)似乎有点不同。 在我没有设置Content-Type标头之前我遇到了CORS问题(使用jQuery,但AngularJs将内容类型设置为“application / json”并导致错误)。

我修复了第一部分,将内容类型设置为text / plain,但现在我得到400 Bad Request Error(仅限AngularJs)。我还尝试使用拦截器删除transformRequest,但它没有用。

我使用AngularJs错了吗?因为我正在考虑,unlinke jQuery,它在后台做了额外的“东西”,制作了一些额外的标题或者没有正确传递数据。

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

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

非常感谢

1 个答案:

答案 0 :(得分:1)

我明白了,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方式发送序列化数据的更好方法吗?

相关问题