Javascript Ajax 请求:拒绝设置不安全的标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33143776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:41:56  来源:igfitidea点击:

Ajax request: Refused to set unsafe header

javascriptajaxuser-agenthttp-referer

提问by Quentin

I am trying to play an audio using Google Text-To-Speech. Therefore I need to post a request to their endpoint with the Referer and the User-Agent properly set. This call should return an MP3 that I can play.

我正在尝试使用 Google Text-To-Speech 播放音频。因此,我需要使用正确设置的 Referer 和 User-Agent 向他们的端点发布请求。这个调用应该返回一个我可以播放的 MP3。

However, I get "Refused to set unsafe header" errors. This is my code. How can I do it?

但是,我收到“拒绝设置不安全的标头”错误。这是我的代码。我该怎么做?

          $.ajax({
            url: 'http://translate.google.com/translate_tts?ie=UTF-8&q=Hello&tl=en&client=t',
            beforeSend: function(xhr) {
                 xhr.setRequestHeader("Referer", "http://translate.google.com/");
                 xhr.setRequestHeader("User-Agent", "stagefright/1.2 (Linux;Android 5.0)");
            }, success: function(data){
                el.mp3 = new Audio(data);
                el.mp3.play();
            }
          });

回答by Quentin

You can't. It is impossible.

你不能。是不可能的。

The specificationrequires that the browser abort the setRequestHeadermethod if you try to set those headers.

如果您尝试设置这些标头,规范要求浏览器中止该setRequestHeader方法。

If you need to set those headers then you'll need to make the request from your server and not your visitor's browser.

如果您需要设置这些标头,那么您需要从您的服务器而不是访问者的浏览器发出请求。

(That said, if you need to be deceptive about the user agent or referer then you are probably trying to use the service in a fashion that the owner of it does not want, so you should respect that and stop trying).

(也就是说,如果您需要对用户代理或推荐人进行欺骗,那么您可能正在尝试以它的所有者不想要的方式使用该服务,因此您应该尊重这一点并停止尝试)。

Also check the "Fetch forbidden header names".

还要检查“获取禁止的标题名称”。

回答by sagar

You can't. It is impossible.

你不能。是不可能的。

The specification requires that the browser abort the setRequestHeadermethod if you try to set standard request headers.

setRequestHeader如果您尝试设置标准请求标头,规范要求浏览器中止该方法。

Instead of that you can set custom header to fulfill your request .

取而代之的是,您可以设置自定义标头来满足您的请求。