Angular:为每个查询设置 Content-Type [英] Angular: set Content-Type per query
问题描述
我需要使用不同于 application/json
的 Content-Type
执行一个查询.更改默认的 $http
选项不是一个变体,因为许多查询仍然使用 JSON 数据执行.
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.
我找到了例子
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);});
但它不想工作 — Content-Type 仍然是一个 application/json
.
But it don't want to work — Content-Type is still a application/json
.
有什么真正的方法可以做到吗?更改 $http
默认值然后恢复不是解决方案.
Is any true way to do it right? Changing $http
defaults and then restoring is not a solution.
推荐答案
您所做的不是在 angularjs 中设置标题的有效方法.
What you are doing is not a valid way to set headers in angularjs.
要添加或覆盖这些默认值,只需添加或删除属性从这些配置对象.为 HTTP 方法添加标头除了 POST 或 PUT,只需添加一个小写的新对象HTTP 方法名称作为键,例如$httpProvider.defaults.headers.get ={ 'My-Header' : 'value' }.
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' }.
参考.https://docs.angularjs.org/api/ng/service/$http- 设置 HTTP 标头"部分
Ref. https://docs.angularjs.org/api/ng/service/$http - "Setting HTTP Headers" section
编辑.
你所做的是对的,但你错过了一件事.
What you're doing is right but you're missing one thing.
在您的场景中它不起作用,因为在使用 application/x-www-form-urlencoded
时,您需要使用 $httpParamSerializerJQLike()
对数据进行编码.还要记得把 $httpParamSerializerJQlike
作为依赖.
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.
这篇关于Angular:为每个查询设置 Content-Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!