繁体   English   中英

使用纯JS对Google API进行CORS POST请求

[英]CORS POST request to google api with pure js

我遇到了Google speeach API的CORS问题。 我需要将音频文件(POST请求)发送到

 https://www.google.com/speech-api/v2/recognize?xjerr=1&client=chromium&lang=en-US&maxresults=10&pfilter=0&xjerr=1&key=MY_KEY

另外我应该指定一个标题Content-Type:audio/l16; rate=44100 Content-Type:audio/l16; rate=44100以帮助Google Speech API正确处理我的请求。

我通过curl尝试了此请求,它有效-我可以收到正确的结果。 但是,当我尝试通过客户端JavaScript执行此操作时,脚本失败并显示错误

跨域请求被阻止:“同源起源”策略不允许在https://www.google.com/speech-api/v2/recognize?xjerr=1&client=chromium&lang=zh-CN&maxresults=10&pfilter=0&xjerr=1&key= MY_KEYI&output = json (原因:CORS标头“ Access-Control-Allow-Origin”缺失)。

我知道服务器不包含Acces-Control-Allow-Origin标头。

我的问题是如何使用纯JavaScript从主机执行对Google API的CORS POST请求?

我刚得到我的Javascript CORS代码,可以对Google Calendar API进行CORS请求,以将电子邮件添加到日历中。 按照它并替换您需要的。 我使用oAuth2进行身份验证,该操作在下面的代码之外进行,因此已经在以下函数之外的全局变量中设置了“ google_access_token”变量:

说明:

*前两行提供并加载Google api(其中包括XMLHttpRequest CORS)*新的XMLHttpRequest()创建CORS对象* requestURL:是API的URL端点,您应将其替换为自己的端点

* params:是要传递数据的JS对象,同样取决于您使用的API

* JSON.stringify(params)将JS数据对象转换为json字符串

* xhr.open('POST',requestURL +'?access_token ='+ encodeURIComponent(google_access_token),true)初始化请求,注意在编码后如何附加access_token

* xhr.setRequestHeader('Content-Type','application / json'):设置http内容类型以指定我以json格式传递数据

*将响应处理程序添加到onload和oneerror事件中

* xhr.send(paramsjasonString),最后发送数据

这是指向Java的Google Client API页面的链接,其中包含有关CORS工作原理的说明。 不幸的是,它的POST示例太简单了,因此我不得不花一些时间弄清楚如何发送更复杂的数据的细节。

 <script src="https://apis.google.com/js/api.js"></script>
      <script type="text/javascript">
       gapi.load('auth2', function() {
        // Library loaded.
      });

      function gapiACL() {
      var xhr = new XMLHttpRequest();
      var requestURL = 'https://www.googleapis.com/calendar/v3/calendars/87sertf1v9os5if1cju785e4@group.calendar.google.com/acl'; 
      var params = {role: "writer",
                      scope: {
                        type: "user",
                        value: "rosamesarina@gmail.com"         
                      }
                    };


       var paramsjasonString = JSON.stringify(params); // convert the javascript object to a Json string
       console.log("paramsjasonString = " + paramsjasonString);

       xhr.open('POST', requestURL + '?access_token=' + encodeURIComponent(google_access_token), true );
       // Specify the http content-type as json
        xhr.setRequestHeader(
         'Content-Type', 'application/json');

       // Response handlers
       xhr.onload = function() {
         var responseText = xhr.responseText;
         console.log(responseText);
         // process the response.
       };

      xhr.onerror = function() {
        console.log('There was an error!');
      };
      xhr.send(paramsjasonString);


    }

暂无
暂无

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

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