简体   繁体   English

使用AngularJS在Firefox中更改请求标头时遇到问题

[英]trouble changing request headers in Firefox with AngularJS

My backend requires the 'Content-Type' request header to be exactly 'application/json'. 我的后端要求'Content-Type'请求标头正好是'application / json'。 This is a CORS request and everything works fine in Chrome. 这是一个CORS请求,Chrome中的一切正常。 The exact header, from developer tools network tab source: 来自开发人员工具网络标签源的确切标题:

Content-Type: application/json

I set this in AngularJS with $http.default.headers.post and it works fine in Chrome. 我在AngularJS中用$ http.default.headers.post设置它,它在Chrome中运行良好。 However it doesn't work in Firefox. 但它在Firefox中不起作用。 Firefox sends this instead: Firefox发送此代码:

Content-Type: application/json; charset=UTF-8

I tried to change headers by: 我试图通过以下方式更改标题:

  • settings $http.default.headers (for .post, .common) settings $ http.default.headers(for .post,.common)
  • setting custom headers for one request 为一个请求设置自定义标头
  • using an $http interceptor 使用$ http拦截器

All of those methods work well in Chrome, but not in Firefox. 所有这些方法都适用于Chrome,但不适用于Firefox。 The request contains data . 该请求包含数据

If I remove the 'Content-Type' header all together, it still is sent, but then it is: 如果我一起删除'Content-Type'标题,它仍然会被发送,但它是:

Content-Type: text/plain; charset=UTF-8

(this happens in both Chrome and Firefox). (这种情况发生在Chrome和Firefox中)。

This leads me to think that the browser forces the header :) How can I circumvent this in Firefox? 这让我觉得浏览器强制标题:)我怎样才能在Firefox中绕过这个?

Firefox has charset=UTF-8 hard-coded for string payloads . Firefox 为字符串有效负载提供了字符串 charset=UTF-8 硬编码

You may however send a Blob instead: 但是你可以发送一个Blob

var r = new XMLHttpRequest();
r.open("POST", ...);
r.send(new Blob(
 [JSON.stringify({a:1})],
 {type:"application/json"}
));

This also works perfectly fine with the angular $http XHR wrapper: 这也适用于角度$http XHR包装:

$http({
    method: "POST",
    url: "/echo/json",
    headers: {
        "Content-Type": "application/json"
    },
    data: new Blob([JSON.stringify({
        a: 1
    })])
});

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM