如何在 AngularJS 中选择内容类型
How to choose content-type in AngularJS
在 AngularJS 中使用 post 时,内容类型总是让我感到困惑。
内容类型:
- urlencoded
- 未定义
...
$http({
headers: {'Content-Type': undefined},
processData: false,
method: 'POST',
cache: false,
url: sendUrl,
data: sendObj,
transformRequest: function (data, headersGetterFunction) {
return data; // do nothing! FormData is very good!
}
})
I post JSON 带有文件对象的数据。
我发现内容类型必须设置为未定义。这里是some clue。但是我不知道为什么必须设置为undefined。
您需要将内容类型设置为 undefined
以便浏览器自行生成。文件上传需要多部分请求,而那些需要部分之间的边界。因此生成的 Content-Type
header 看起来像这样:
Content-Type=multipart/form-data; boundary=---------------------------99614912995
注意 boundary=
。该值由浏览器生成,不能自行设置。
您需要设置 transformRequest
的原因是,否则 Angular 会将您的数据发送为 JSON,因为这是默认转换。但你可以缩短它:
transformRequest: angular.identity,
在 AngularJS 中使用 post 时,内容类型总是让我感到困惑。 内容类型:
- urlencoded
- 未定义
...
$http({ headers: {'Content-Type': undefined}, processData: false, method: 'POST', cache: false, url: sendUrl, data: sendObj, transformRequest: function (data, headersGetterFunction) { return data; // do nothing! FormData is very good! } })
I post JSON 带有文件对象的数据。
我发现内容类型必须设置为未定义。这里是some clue。但是我不知道为什么必须设置为undefined。
您需要将内容类型设置为 undefined
以便浏览器自行生成。文件上传需要多部分请求,而那些需要部分之间的边界。因此生成的 Content-Type
header 看起来像这样:
Content-Type=multipart/form-data; boundary=---------------------------99614912995
注意 boundary=
。该值由浏览器生成,不能自行设置。
您需要设置 transformRequest
的原因是,否则 Angular 会将您的数据发送为 JSON,因为这是默认转换。但你可以缩短它:
transformRequest: angular.identity,