hulkyuan hulkyuan - 1 year ago 106
AngularJS Question

How to choose content-type in AngularJS

When use post in AngularJS the content-type always confused me.

  1. urlencoded

  2. undefined

  3. ...

    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 data with file object.

I found out the content-type must set to undefined. Here is some clue. But I dont know why must set to undefined.

Answer Source

You need to set the content type to undefined so that the browser generates one itself. File uploads require multipart requests and those require boundaries between the parts. Thus a generated Content-Type header looks like this:

Content-Type=multipart/form-data; boundary=---------------------------99614912995

Note the boundary=. The value is generated by the browser and you cannot set it yourself.

The reason why you need to set transformRequest is that otherwise Angular would send your data as JSON, because that's the default transformation. But you can have it shorter:

transformRequest: angular.identity,  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download