Ajax 请求:拒绝设置不安全的标头 [英] Ajax request: Refused to set unsafe header

查看:52
本文介绍了Ajax 请求:拒绝设置不安全的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

但是,我收到 Refused to set unsafe header 错误.这是我的代码.我该怎么做?

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

          $.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();
            }
          });

推荐答案

你不能.这是不可能的.

You can't. It is impossible.

规范 要求浏览器中止 setRequestHeader 方法,如果您尝试设置 Referer 标头(它曾经是 User-Agent 也被禁止,但现在已经改变了).

The specification requires that the browser abort the setRequestHeader method if you try to set the Referer header (it used to be that User-Agent was also forbidden but that has changed)..

如果您需要手动设置Referer,那么您需要从您的服务器而不是访问者的浏览器发出请求.

If you need to set Referer manually 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).

请注意,虽然 jQuery 包装了 XHR,但同样的规则适用于 fetch.

Note that while jQuery wraps XHR, the same rules apply to fetch.

这篇关于Ajax 请求:拒绝设置不安全的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆