角:每次查询设置Content-Type的 [英] Angular: set Content-Type per query
问题描述
我需要执行与一个查询的内容类型
比应用程序/ JSON
不同。
更改默认 $ 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);});
但它不想工作 - 内容类型仍然是一个应用程序/ 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 =
{我的报头':'值'}
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.
在您的情况,因为使用时无法正常工作应用程序/ x-WWW的形式urlen codeD
您使用需要连接code数据 $ 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.
这篇关于角:每次查询设置Content-Type的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!