2

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

  1. urlencoded
  2. undefined
  3. ...

    $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 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.

1 Answer 1

1

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,  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.