Arman Hayots
Arman Hayots

Reputation: 2508

Angular: set Content-Type per query

I need to perform one query with Content-Type different than application/json. Changing default $http options is not a variant, because a lot of queries still be performed with JSON data.

I've found example

var req = {
            method: 'POST',
            url: 'example.com',
            headers: {
                'Content-Type': "application/x-www-form-urlencoded"
            },
            data:  "somedata"
            }

 $http(req).then(function (resp) { console.log(resp);});

But it don't want to work — Content-Type is still a application/json.

Is any true way to do it right? Changing $http defaults and then restoring is not a solution.

Upvotes: 1

Views: 319

Answers (1)

Chris Hermut
Chris Hermut

Reputation: 1758

What you are doing is not a valid way to set headers in angularjs.

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.

Ref. https://docs.angularjs.org/api/ng/service/$http - "Setting HTTP Headers" section

Edit.

What you're doing is right but you're missing one thing.

In your scenario it does not work because when using application/x-www-form-urlencoded you need to encode your data using $httpParamSerializerJQLike(). Also remember to put $httpParamSerializerJQLike as dependency.

Upvotes: 1

Related Questions