问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/34293376/angular-set-content-type-per-query