Ajax request: Refused to set unsafe header

岁酱吖の 提交于 2020-06-24 19:37:43

问题


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.

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

回答1:


You can't. It is impossible.

The specification requires that the browser abort the setRequestHeader method if you try to set those headers.

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".



来源:https://stackoverflow.com/questions/33143776/ajax-request-refused-to-set-unsafe-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!