Using vanilla JavaScript, make a Cross-Origin Resource Sharing (CORS) POST request to

I encountered a CORS issue while using the Google Speech API. I am trying to send an 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

I also need to specify a header

Content-Type:audio/l16; rate=44100
to ensure that my request is processed correctly by Google Speech API.

I was successful in making this request using curl, and it returned accurate results. However, when attempting the same request in client-side JavaScript, I received the following error:

Cross-Origin Request Blocked: The Same Origin Policy prevents 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 have realized that the server is lacking the Acces-Control-Allow-Origin header.

My query is how can I make a CORS POST request to the Google API from my host using pure JavaScript?

Answer №1

Successfully implemented my JavaScript CORS code to make requests to the Google Calendar API for adding emails to the calendar. Feel free to use and modify as needed. I have utilized oAuth2 for authentication, with the "google_access_token" variable already set globally outside the function.

Here's a breakdown:

*The first two lines fetch and load the necessary Google APIs (including XMLHttpRequest for CORS) *Using new XMLHttpRequest() to create the CORS object *requestURL is the API endpoint URL; ensure to replace it with your specific endpoint

*params is a JS object containing the data you wish to send, tailored to the specific API being utilized

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

*xhr.open('POST', requestURL + '?access_token=' + encodeURIComponent(google_access_token), true ) initializes the request, note the encoding of the access token

*xhr.setRequestHeader( 'Content-Type', 'application/json') sets the content-type to specify JSON format for data transmission

*Attach response handlers to the onload and onerror events

*Finally, send the data using xhr.send(paramsjasonString)

Refer to the Google Client API for JavaScript page for insights on CORS functionality. The provided POST example may be simplistic, necessitating deeper exploration to handle more complex data formatting.

 <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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99a1aeeafcebedffa8efa0f6eaacf0ffa8faf3ecaea1acfcadd9feebf6ece9b7faf8f5fcf7fdf8ebb7fef6f6fef5fcb7faf6f4">[email protected]</a>/acl'; 
      var params = {role: "writer",
                      scope: {
                        type: "user",
                        value: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25574a564448405644574c4b44654248444c490b464a48">[email protected]</a>"         
                      }
                    };


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


    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered when attempting to embed a SoundCloud player in Angular 4: Unable to execute 'createPattern' on 'CanvasRenderingContext2D' due to the canvas width being 0

I attempted to integrate the SoundCloud iframe into my Angular 4 component, but encountered the following error message: Failed to execute 'createPattern' on 'CanvasRenderingContext2D': The canvas width is 0. Here is the iframe code ...

Tips for fading an image as you scroll using CSS and JavaScript?

I have been dedicating my day to mastering the art of website development. However, I am facing a challenge that is proving to be quite difficult. I am looking to create a smooth transition effect where an image gradually blurs while scrolling down, and re ...

"Adjusting the height of a div element while considering the

I have 2 elements with different heights and I want to make them equal: var highestEl = $('#secondElement').height(); $('.element').first().height(highestEl); I understand that the second element is always taller than the first one. W ...

SyntaxError: End of input caught unexpectedly (NodeJS TCP server)

My simple tcp server has the capability to send and receive json data. Here is a snippet of my code: // Handling incoming messages from clients. socket.on('data', function (data) { var obj = JSON.parse(data); if(obj.type == "regis ...

Adding participants using the Google Calendar API in JavaScript: A step-by-step guide

I am attempting to include attendees in a Google Calendar event using the API. The method I am currently using, similar to the update function, is not working as expected and is removing all previous attendees. Below is the code snippet: const attendees ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...

Troubles with Vue and localStorage for storing a theme's data

I've been struggling with this issue for a while now while working on a Vue site. I have not been able to find a solution for my specific bug in other discussions. The concept should be straightforward - I want to have a switch that toggles a value b ...

Steps to create inactive HTML with a loading GIF displayed

When the sign-up button is clicked, a modal pops up. After inputting data, upon hitting the "sign up" button, I would like the actual popup's HTML content to become inactive and display a loading GIF icon in the center until an AJAX response is receiv ...

What could be causing my AngularJS JSONP request to fail when trying to query Solr?

After attempting to query my Solr server with the provided code snippet: var url ="http://localhost:8080/solr/sdc/selectwt=json&callback=JSON_CALLBACK&q=opioid" $http.jsonp(url ).success(function(res){ console.log(res) }) An error is returned ...

Need for input

I am working on organizing my routes in a separate file from app.js. The login route requires access to a Firebase instance. routes/auth.js var express = require('express'); var router = express.Router(); module.exports = function(firebase) { ...

"Adjusting the position of series data container in Highcharts JS to optimize

Currently, I am utilizing highcharts along with highcharts-ng. My goal is to adjust the position of the container for series Data (where the number 80 is displayed below) slightly higher as it is currently overlapping with the numbers 200 and -200 in the t ...

Exploring ways to dynamically alter templates using the link function in Angular.js

Recently, I developed a directive called widget which functions similar to ng-view, but the template name is derived from an attribute. app.directive('widget', function() { return { restrict: 'EA', scope: true, ...

Determining whether an element possesses an attribute labeled "name" that commences with a specific term, apart from the attribute "value"

I'm planning to use distinctive data attributes with a prefix like "data-mo-". Let's say I have the following elements: <span data-mo-top-fade-duration="600">Title 1</span> <span data-mo-bottom-fade-duration="600">Title 2</ ...

Issue: Module 'blog' not found in the specified path in my Node.js application

this snippet showcases my code in routes/blog.js var express = require('express'); var router = express.Router(); const Blogs = require("../models/blog"); and here is the code from models/blog.js const mongoose = require('mongoose ...

Combining CSS and JavaScript to handle two events with a single onClick

Here is the code I've created: <a href="#" id="home" class="showLink" onclick="showHide('example');return false;"> <li class="buttons">home</li> </a> <a href="#" id="user" class="showLink" onclick="showHide(&a ...

Harnessing the Power: Ajax Combined with JQuery

I am facing an issue with my function where I make an ajax request, wait for a response, and return a value but the returned value is coming out as undefined. What could be causing this problem? function RetrieveDataFromURL(url){ return $.ajax({ ...

Is there a way for me to manage the appearance of the printed document's layout?

I have successfully added 3 print buttons to my website, each one designed to print a specific portion (div) of the webpage. Here is the code snippet for this functionality: function printPage(id) { var html="<html>"; //html+="<link rel="st ...

The array is present both before and after the res.json() call, however it appears empty in the response

When using Express to send a json response with res.json(), I am experiencing an issue where the value of records in the object sent via res.json() is empty. My code snippet looks like this: stats.activities(params).then(res => { processActivities ...

Maximizing the Efficiency of Three js with Image Textures for Faster Performance

I have some code to share, but unfortunately, I don't have the images to upload along with it. Within the code, there are two functions present: UseMeshNormalMaterial() and UsePngMaterial(). This setup allows you to easily test the code if you happ ...

Having an issue with passing memoryStorage to Express using Multer and Ajax, as the req.file object is coming

Looking through multiple posts on Stack Overflow, I found that many are discussing the issue of req.file being undefined. However, the solutions provided didn't seem to address my specific problem. Here is the HTML code (Pug) I am using: ...