Challenges when sending a POST request to Google Cloud Vision using JavaScript

My aim is to send a simple POST request to Google Cloud Vision API using javascript and jquery. When testing in Chrome, I encounter a 400 error in the console without any additional information for debugging. I'm hoping that someone with experience in Cloud Vision can pinpoint where I might be going wrong, especially when it comes to formatting the request body (data). The complete test code is shown below:

<html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/json2/20160511/json2.js"></script>
<script type="text/javascript">

var p = {"requests":[{  "image":{    "source":{"imageUri":"https://cloud.google.com/vision/docs/images/car.png"}}  ,  "features": [{"type":"LABEL_DETECTION","maxResults":3}]    } ]};

$.ajax({
type: "POST",
url: "https://vision.googleapis.com/v1/images:annotate?key=APIKEY",
data: JSON.stringify(p),

headers: {
  "Content-Type": "application/json",
},

dataType: "json",   
success: function(data, textStatus, jqXHR) {
  alert(data);
}

});

</script>
</head></html>

I have consulted the following documentation for assistance: https://cloud.google.com/vision/docs/detecting-labels, but without success.

For your information, I have also attempted using the shorthand method, but it resulted in the same error:

var p = {"requests":[{  "image":{    "source":{"imageUri":"https://cloud.google.com/vision/docs/images/car.png"}}  ,  "features": [{"type":"LABEL_DETECTION","maxResults":3}]    } ]};
$.post( "https://vision.googleapis.com/v1/images:annotate?key=APIKEY", JSON.stringify(p) , function(data) { alert(data); }       );

Answer №1

After successfully implementing the code below without any complications, I am no longer interested in the previous jquery solution :)

<script type="text/javascript>
var data = JSON.stringify({
  "requests": [
    {
      "image": {
        "source": {
          "imageUri": "https://cloud.google.com/vision/docs/images/car.png"
        }
      },
      "features": [
        {"type": "LABEL_DETECTION", "maxResults":5}
      ]
    }
  ]
});

var request = new XMLHttpRequest;

request.onload = function() {
  console.log(request.responseText);
};

request.open("POST", "https://vision.googleapis.com/v1/images:annotate?key=APIKEY", true);
request.send(data);
</script>

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

How can I move a TableItem from one material UI component to another using drag-and-drop?

I am facing an issue where I need to drag a ListItem from one List component to another. I am uncertain about how to accomplish this in Material UI. ...

A div containing a form, with the form being visually integrated within the div

Hi everyone, this is my first post here and I've tried to search extensively before asking this question. I've attempted to use the following examples without success: jquery submit form and then show results in an existing div Form submit ...

The most effective method for verifying a user's login status using node.js and express and updating the client-side HTML

For my web application, I am using node.js and express along with sessions in mongoDB to handle server side code like this: exports.home = function(req, res){ if(req.session.userEnabled){ console.log("logged"); res.render('home', { title ...

Modify MUI's ListItemText component by targeting a specific span to implement customized styles using the useStyle hook

It's quite perplexing that although this is a straightforward task in regular CSS, it must be accomplished through MUI's useStyles for some peculiar reason. Essentially, I possess a ListItem containing a ListItemText. It appears as follows: cons ...

The essence of my design disappears when I generate a canvas object using Fabric.js

After defining top and left attributes for a Canvas Object using a JavaScript function, I encounter an issue when creating a fabric Canvas object. var fabricCanvas = new fabric.Canvas('mycanvas'); Upon creation, my HTML Canvas has its top and ...

How can we use Selenium to inject and execute Javascript on a page before loading or running any other scripts on the page?

Currently, I am utilizing the Selenium Python WebDriver to navigate various web pages. My objective is to inject a JavaScript code into these pages before any other JavaScript codes are loaded and executed. However, it is crucial that my JS code is the fir ...

Accessing JSON data from a database using Angular

Wondering if there is a way to effectively access and manipulate JSON data stored in a database using Angular. While researching online, I keep coming across methods for reading JSON files from the Asset Folder, which does not align with what I need. What ...

What could be the reason that step 3 of the AngularJS Tutorial is not functioning correctly?

During Step 3 of the AngularJS Tutorial, an additional e2e test is recommended to enhance the example: it('should display the current filter value within an element with id "status"', function() { expect(element('#status').text() ...

Unveiling the magic of Vue Composition API: Leveraging props in the <script setup> tag

I'm currently working on creating a component that takes a title text and a tag as properties to display the title in the corresponding h1, h2, etc. tag. This is my first time using the sweet <script setup> method, but I've encountered a pr ...

Encountering difficulties in creating an app with Apache Cordova

After setting up the proxy settings, I attempted to create a new app named "hello" using Cordova with the following commands: npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 The creation comman ...

Parsing custom fields with GSON on Android using Retrofit2

Here is the JSON object I am working with: { "attributes": { "date": "2016-01-01" }, "first": "05:33", "second": "05:50", "third": "07:22" } Typically, when parsing this JSON using Gson retrofit parser, we would create a class ...

The callback assigned to the state variable of the Context Provider will not be defined

I have examined previous questions asked by OPs here, but none of the solutions seem to work for me. The issue I am facing involves a layout with a toolbar used to submit forms. To achieve this, I am employing a FormProvider as a Context.Provider that wrap ...

Automating the Process of File Downloads Using Ajax and PHP

I am currently working on a form that requires users to enter a secret key. Once the key is submitted, it is verified against a database. If the key is found, the relevant file associated with the key should be downloaded automatically. I have successfully ...

Having trouble loading services within my Angular controller

After developing my Angular application, I added some basic code to my controller which is displayed below. Now, I am attempting to include two services that I created in my services.js file. This file is being loaded in my index.html and required within m ...

What is the best way to incorporate v-divider components in between each v-list-item?

I'm attempting to create multiple v-dividers based on the number of answers I have, so that there is a divider for each answer (4). Following an example from the official documentation, I'm trying something like this but I seem to be stuck. Could ...

Upon refreshing the browser page, AngularJS fails to redirect to the default page as expected

In my AngularJS route configuration, I have set up the following paths: moduleA.config(function($routeProvider){ $routeProvider. when('/A',{templateUrl:'A.jsp'}). when('/B',{templateUrl:'B.jsp'}). wh ...

What is the best way to hear an event emitted by a component?

I am trying to listen for an event in Chrome DevTools Vue, but I'm not sure how to target it. For a Root event, I typically use: this.$root.$on("note_id", (note_id) => (this.note_id = note_id)); But how do I address an event that origina ...

Is there a way to showcase multiple TableViews from a Json File using Swift?

I am looking to populate a TableView in Xcode (Swift) with information from a Json file. To illustrate, here is what I aim to achieve: My goal is to extract json data regarding countries, cities, and additional city details. On the initial screen, I want ...

Is ES5 essentially the same as ES6 in terms of my lambda search?

After doing a search on an array using ES6, I am having trouble figuring out how to rewrite the code in ES5 due to restrictions with Cordova not allowing me to use lambda functions... $scope.Contact.title = $scope.doctitles[$scope.doctitles.findIndex(fu ...

The playwright brings the curtain down on a blank page without a single word

I am working with code snippets const {chromium} = require('playwright'); (async () => { const userDataDir = '\NewData'; const browser = await chromium.launchPersistentContext(userDataDir,{headless:false}); const pag ...