【问题标题】:400 Bad Request only using AngularJs, works with jQuery400 Bad Request 仅使用 AngularJs,适用于 jQuery
【发布时间】:2015-04-05 10:35:35
【问题描述】:

我在使用 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 将 content-type 设置为“application/json”并导致错误)。

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

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

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

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

非常感谢

【问题讨论】:

  • 使用 Wireshark 准确查看每种情况下传递的标头。
  • 只需比较两种情况下发送的标头即可。有区别。
  • 我考虑过这样做,但我正在使用拦截器进行调试,记录每个调用的配置对象和响应。从我所看到的看来一切都是正确的,但实际上它不起作用
  • 最好比较“电线”上的实际情况。如果不是 Wireshark,请至少使用开发者工具。
  • 我认为应该是 Content-Type 而不是 Content-type 。但也许这不是原因,这是因为他们以不同的方式转换数据对象

标签: javascript jquery ajax angularjs rest


【解决方案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 形式发送序列化数据的更好方法吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 2015-07-22
    • 1970-01-01
    • 2016-11-18
    • 2011-09-25
    • 1970-01-01
    • 2012-09-07
    • 2016-03-16
    相关资源
    最近更新 更多