【问题标题】:Adding header to angular POST causes request body to be empty将标头添加到角度 POST 会导致请求正文为空
【发布时间】:2017-01-15 23:43:27
【问题描述】:

我正在使用 Angular 将文件发布到 Amazon S3 存储桶。为了让存储桶接受请求,我尝试向其添加 Upgrade-Insecure-Requests 标头,当我这样做时,请求不再具有正文。

此代码正确发送请求正文:

$http({
  method: "POST",
  url: responseData.url,
  data: postData,
  headers: {"Content-Type": undefined},
  transformRequest: angular.identity
})

虽然此代码导致请求正文为空:

$http({
  method: "POST",
  url: responseData.url,
  data: postData,
  headers: {"Content-Type": undefined,
            "Upgrade-Insecure-Requests": "1"},
  transformRequest: angular.identity
})

这可能是什么原因造成的?

编辑:我发现没有请求正文的原因是因为预检 OPTIONS 请求被发送到 S3。我在存储桶中添加了一个 CORS 策略,允许使用 OPTIONS 和 POST 方法,所以现在 OPTIONS 请求可以正确返回。

但是在收到 OPTIONS 响应后,没有进行任何 POST,即使 POST 应该满足要求。

这些是 OPTIONS 的请求标头:

OPTIONS / HTTP/1.1
Host: tesssssst-aws-cms.s3.amazonaws.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: https://s3.amazonaws.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Access-Control-Request-Headers: cache-control, upgrade-insecure-requests
Accept: */*
Referer: https://s3.amazonaws.com/tesssssst-aws-cms/HTML/upload.html
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,ms;q=0.4,th;q=0.2

这些是 OPTIONS 的响应标头:

HTTP/1.1 200 OK
x-amz-id-2: SQaOyODgprPIRe8uq3YEZBDXzVcUjyYc2GpLsZwmIwdII+FVIgOGQXokIzXTsBcIaOITgwrk8Zw=
x-amz-request-id: 07EE6477F2B3273C
Date: Thu, 08 Sep 2016 07:12:58 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, GET, POST
Access-Control-Allow-Headers: cache-control, upgrade-insecure-requests
Access-Control-Max-Age: 3000
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
Content-Length: 0
Server: AmazonS3

【问题讨论】:

  • app.config(['$httpProvider', function ($httpProvider) { $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest'; }]);
  • @mehrdad 添加这个会破坏页面上另一个当前工作的 POST 请求。有什么方法可以专门将其添加到请求中?
  • 我也用它来发送数据到 header $http({ url: $scope.path + '/Account/EditUserAngular', method: 'Post', headers: { 'RequestVerificationToken': $scope .antiForgeryToken, 'IsMobile': "true", "X-Requested-With": "XMLHttpRequest" }, 数据: { model: $scope.UserEditViewModel, } })
  • 将“X-Requested-With”标头添加到请求标头中并没有改变任何东西。

标签: angularjs http-post preflight


【解决方案1】:

“升级不安全请求”:“1” 导致您的帖子请求作为选项发送我遇到了同样的问题,所以我删除了上面的行并且它起作用了。 之后我面临新的错误跨域问题但是,当我检查提琴手时,一切都很好。 那是浏览器(Chrome)的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-29
    • 2015-07-17
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多