【问题标题】:$http data vs params when making POST request发出 POST 请求时的 $http 数据与参数
【发布时间】:2017-06-14 06:12:44
【问题描述】:

前言:我使用的是 AngularJS 1.5.9。

在编写我的服务时,此代码在发布到服务器时有效:

var request = {
    url: '/connect/token',
    method: 'POST',
    data: $httpParamSerializer(params),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
};
$http(request).then(function(response) {});

但是,当 $http 具有使用参数 params 时使用 data 似乎违反直觉,根据 AngularJS's documentation 的定义如下:

params – {Object.} – 字符串或对象的映射 将使用 paramSerializer 序列化并附加为 GET 参数。

如您所见,文档指定此参数仅用于 GET 请求。当我尝试在我的 POST 请求中使用 params 参数时,我也确认了这一点:

var request = {
    url: '/connect/token',
    method: 'POST',
    params: params,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
};
$http(request).then(function(response) {});

当你以这种方式提交 POST 请求时,你会从服务器得到如下响应:

{
    "error":"invalid_request",
    "error_description":"A malformed token request has been received: the mandatory 'Content-Type' header was missing from the POST request."
}

换句话说,如果我不使用 data 参数并在我想要传入的参数上调用参数序列化程序服务,我的自定义服务不会在我的请求中设置 Content-Type 标头,我已经在网络检查器的网络选项卡中确认了这一点。

TLDR; 为什么我必须使用 data 参数并序列化参数,而不是直接使用 params 参数?当我使用 params 参数时,为什么我指定的内容类型会被忽略?

【问题讨论】:

  • params 用于URL查询参数,你的POST请求需要有一个body
  • 你一针见血。谢谢!只需发布一个答案,我就会给你功劳。如果您愿意提供任何细节,请务必感谢:) @jonrsharpe

标签: angularjs xmlhttprequest


【解决方案1】:

GET 请求使用params 选项。

使用params 选项,您可以设置URL 查询字符串参数,例如baseurl.com?myParam=something

【讨论】:

    猜你喜欢
    • 2016-05-14
    • 1970-01-01
    • 2016-06-02
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多