Angular: set Content-Type per query

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 15:53:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!