简体   繁体   中英

CORS POST request to google api with pure js

I faced with CORS problem with google speeach API. I need to send audio file (POST request) to

 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 to help Google Speech API process my request correctly.

I tried this request via curl and it works - I can receive correct results. However, when I'm trying to do this via client JavaScript, script fails with error

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 . (Reason: CORS header 'Access-Control-Allow-Origin' missing).

I understood that server doesn't contain Acces-Control-Allow-Origin header.

My question is how to perform CORS POST request to Google API from my host using pure JavaScript?

I just got my Javascript CORS code to work to do CORS request to Google Calendar API to add emails to the calendar. 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:

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

*params: is the JS object with the data you want to pass, again this depends on the API you are using

*JSON.stringify(params) converts the JS data object to a json string

*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.setRequestHeader( 'Content-Type', 'application/json'): sets the http content-type to specify that I am passing data in json format

*add the response handlers to the onload and oneerror events

*xhr.send(paramsjasonString), finally send the data

Here is a link to the Google Client API for Javascript page with explanations on how CORS works. 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.

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


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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