Angular:为每个查询设置内容类型

Angular: set Content-Type per query

我需要执行一项 Content-Type 不同于 application/json 的查询。 更改默认 $http 选项不是变体,因为许多查询仍然使用 JSON 数据执行。

我找到了示例

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

有什么正确的方法吗?更改 $http 默认值然后恢复不是解决方案。

您正在做的不是在 angularjs 中设置 headers 的有效方法。

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 - "Setting HTTP Headers" 部分

编辑。

你做的是对的,但你错过了一件事。

在您的方案中它不起作用,因为在使用 application/x-www-form-urlencoded 时您需要使用 $httpParamSerializerJQLike() 对数据进行编码。还要记住将 $httpParamSerializerJQLike 作为依赖项。