Mugen
Mugen

Reputation: 9095

Cannot set 'Content-Type' header for GET requests

I'm trying to set my GET requests to have the following header:

Content-Type: application/json

According to the documentation, I should set the following:

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' }

However, the following line in my app.ts does not compile:

mainapp.config(($httpProvider: ng.IHttpProvider) => {
        $httpProvider.defaults.headers.get = {"Content-Type" : "application/json";
    });

And the error is that the type of get is string|(() => string).

I've tried to set

mainapp.config(($httpProvider: ng.IHttpProvider) => {
    $httpProvider.defaults.headers.get = "Content-Type: application/json";
});

But it has no effect over my GET requests.

Thanks for any help.

Upvotes: 0

Views: 3076

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

I'm trying to set my GET requests to have the following header:

Content-Type: application/json

But this doesn't make any sense. By definition a GET request doesn't have a body, so trying to specify a content type for something that doesn't exist, hmm...

Didn't you rather mean to set the Accept header to application/json? This would have made much more sense because this way you would indicate to the remote server how do you expect the response body from your GET request to be encoded.

As far as why your code doesn't compile is concerned, you seem to have missed a closing curly brace here. You may try setting the header like this but please note that this is wrong and a terrible workaround that shouldn't be done. Normally you should fix your broken server which enforces you to have a Content-Type header for a GET request.

if (!$httpProvider.defaults.headers.get) {
    $httpProvider.defaults.headers.get = { };
}
$httpProvider.defaults.headers.get["Content-Type"] = "application/json";

Upvotes: 2

Related Questions