简体   繁体   English

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

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

I faced with CORS problem with google speeach API. 我遇到了Google speeach API的CORS问题。 I need to send audio file (POST request) to 我需要将音频文件(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

Also I should specified a header Content-Type:audio/l16; rate=44100 另外我应该指定一个标题Content-Type:audio/l16; rate=44100 Content-Type:audio/l16; rate=44100 to help Google Speech API process my request correctly. Content-Type:audio/l16; rate=44100以帮助Google Speech API正确处理我的请求。

I tried this request via curl and it works - I can receive correct results. 我通过curl尝试了此请求,它有效-我可以收到正确的结果。 However, when I'm trying to do this via client JavaScript, script fails with error 但是,当我尝试通过客户端JavaScript执行此操作时,脚本失败并显示错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/speech-api/v2/recognize?xjerr=1&client=chromium&lang=en-US&maxresults=10&pfilter=0&xjerr=1&key=MY_KEYI&output=json . 跨域请求被阻止:“同源起源”策略不允许在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 (Reason: CORS header 'Access-Control-Allow-Origin' missing). (原因:CORS标头“ Access-Control-Allow-Origin”缺失)。

I understood that server doesn't contain Acces-Control-Allow-Origin header. 我知道服务器不包含Acces-Control-Allow-Origin标头。

My question is how to perform CORS POST request to Google API from my host using pure JavaScript? 我的问题是如何使用纯JavaScript从主机执行对Google API的CORS POST请求?

I just got my Javascript CORS code to work to do CORS request to Google Calendar API to add emails to the calendar. 我刚得到我的Javascript CORS代码,可以对Google Calendar API进行CORS请求,以将电子邮件添加到日历中。 Follow it and replace what you need. 按照它并替换您需要的。 I use oAuth2 for authentication, which I do outside the code below, so the "google_access_token" variable has already been set in a global variable outside the function below: 我使用oAuth2进行身份验证,该操作在下面的代码之外进行,因此已经在以下函数之外的全局变量中设置了“ google_access_token”变量:

Explanation: 说明:

*First two lines source and load the Google apis (which would include the XMLHttpRequest CORS) *new XMLHttpRequest() creates the CORS object *requestURL: is the URL end point for the API, you should replace this with your own end point *前两行提供并加载Google api(其中包括XMLHttpRequest CORS)*新的XMLHttpRequest()创建CORS对象* requestURL:是API的URL端点,您应将其替换为自己的端点

*params: is the JS object with the data you want to pass, again this depends on the API you are using * params:是要传递数据的JS对象,同样取决于您使用的API

*JSON.stringify(params) converts the JS data object to a json string * JSON.stringify(params)将JS数据对象转换为json字符串

*xhr.open('POST', requestURL + '?access_token=' + encodeURIComponent(google_access_token), true ) initializes the request, noticed how I attached the access_token after encoding it * xhr.open('POST',requestURL +'?access_token ='+ encodeURIComponent(google_access_token),true)初始化请求,注意在编码后如何附加access_token

*xhr.setRequestHeader( 'Content-Type', 'application/json'): sets the http content-type to specify that I am passing data in json format * xhr.setRequestHeader('Content-Type','application / json'):设置http内容类型以指定我以json格式传递数据

*add the response handlers to the onload and oneerror events *将响应处理程序添加到onload和oneerror事件中

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

Here is a link to the Google Client API for Javascript page with explanations on how CORS works. 这是指向Java的Google Client API页面的链接,其中包含有关CORS工作原理的说明。 Unfortunately, its POST example is too simple so I had to spend some time figuring out the details of how to send more complex data. 不幸的是,它的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