encountered an error when attempting to utilize the Google Index API in JavaScript

Greetings everyone, I am interested in creating a script that updates the new URLs of my website using the Google Indexing API from http://localhost:8000/test.html. I have added http://localhost:8000 to Authorized JavaScript origins in the client ID, but I encountered error 400:

Sign-in successful

cb=gapi.loaded_0:228 GET https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest?pp=0&fields=kind%2Cname%2Cversion%2CrootUrl%2CservicePath%2Cresources%2Cparameters%2Cmethods%2CbatchPath%2Cid&key='my api' 400
wh @ cb=gapi.loaded_0:228
g @ cb=gapi.loaded_0:228
xh @ cb=gapi.loaded_0:229
(anonymous) @ cb=gapi.loaded_0:229
d @ cb=gapi.loaded_0:186
b @ cb=gapi.loaded_0:181


Error loading GAPI client for API 
{error: {…}}
error:
code: 400
message: "Request contains an invalid argument."
status: "INVALID_ARGUMENT"
__proto__: Object
__proto__: Object

I tried switching from Chrome to Edge and it worked once, but upon restarting my PC, the problem resurfaced. I am utilizing the API explorer script available at: link. The script and console log details are also provided as an image.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

</head>

<body>
  <script src="https://apis.google.com/js/api.js"></script>
  <script>
    /**
     * Sample JavaScript code for indexing.urlNotifications.publish
     * See instructions for running APIs Explorer code samples locally:
     * https://developers.google.com/explorer-help/guides/code_samples#javascript
     */

    function authenticate() {
      return gapi.auth2.getAuthInstance()
        .signIn({
          scope: "https://www.googleapis.com/auth/indexing"
        })
        .then(function() {
            console.log("Sign-in successful");
          },
          function(err) {
            console.error("Error signing in", err);
          });
    }

    function loadClient() {
      gapi.client.setApiKey("My-API");
      return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
        .then(function() {
            console.log("GAPI client loaded for API");
          },
          function(err) {
            console.error("Error loading GAPI client for API", err);
          });
    }
    // Make sure the client is loaded and sign-in is complete before calling this method.
    function execute() {
      return gapi.client.indexing.urlNotifications.publish({
          "resource": {
            "url": "example",
            "type": "URL_UPDATED"
          }
        })
        .then(function(response) {
            // Handle the results here (response.result has the parsed body).
            console.log("Response", response);
          },
          function(err) {
            console.error("Execute error", err);
          });
    }
    gapi.load("client:auth2", function() {
      gapi.auth2.init({
        client_id: "my OAuth client ID"
      });
    });
  </script>
  <button onclick="authenticate().then(loadClient)">authorize and load</button>
  <button onclick="execute()">execute</button>
</body>

</html>

Here's the console log

Answer №1

Thank God, I attempted to loadClient and authenticate, and it successfully worked

It was done in this way <button onclick="loadClient().then(authenticate)">authorize and load</button>

After that, I switched to chrome incognito mode

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
 
</head>

<body>
  <script src="https://apis.google.com/js/api.js"></script>
  <script>
    /**
     * Sample JavaScript code for indexing.urlNotifications.publish
     * See instructions for running APIs Explorer code samples locally:
     * https://developers.google.com/explorer-help/guides/code_samples#javascript
     */

    function authenticate() {
      return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/indexing"})
        .then(function () { console.log("Sign-in successful"); },
          function (err) { console.error("Error signing in", err); });
    }
    function loadClient() {
      gapi.client.setApiKey("My API");
      return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
        .then(function () { console.log("GAPI client loaded for API"); },
          function (err) { console.error("Error loading GAPI client for API", err); });
    }
    // Make sure the client is loaded and sign-in is complete before calling this method.
    function execute() {
      return gapi.client.indexing.urlNotifications.publish({
        "resource": {
          "url": "my web site",
          "type": "URL_UPDATED"
        }
      })
        .then(function (response) {
          // Handle the results here (response.result has the parsed body).
          console.log("Response", response);
        },
          function (err) { console.error("Execute error", err); });
    }
    gapi.load("client:auth2", function () {
      gapi.auth2.init({client_id:"My client ID"});
    });
  </script>
  <button onclick="loadClient().then(authenticate)">authorize and load</button>
  <button onclick="execute()">execute</button>
</body>

</html>

GAPI client loaded for API
Sign-in successful
Response {result: {…}, body: "{↵  "urlNotificationMetadata": {↵    "url": "https…e": "2020-09-15T20:34:07.091671446Z"↵    }↵  }↵}↵", headers: {…}, status: 200, statusText: null}

Answer №2

<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Unique JavaScript code for indexing.urlNotifications.publish
   * Utilize instructions provided to run APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/indexing"})
        .then(function() { console.log("Successfully signed in"); },
              function(err) { console.error("Error while signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("yyyyyyyyyyyyyyyyyy");
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
        .then(function() { console.log("GAPI client loaded successfully for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Ensure the client is loaded and sign-in is completed before calling this method.
  function execute() {
    return gapi.client.indexing.urlNotifications.publish({
      "resource": {}
    })
        .then(function(response) {
                // Process the results here (response.result contains parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "sampleyyyyyyyyyyyyyyyyy.apps.googleusercontent.com"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

issue persists and

<script src="https://apis.google.com/js/api.js"></script>
    <script>
      /**
       * Customized JavaScript code for indexing.urlNotifications.publish
       * Refer to running APIs Explorer code sample guidelines:
       * https://developers.google.com/explorer-help/code-samples#javascript
       */
    
      function authenticate() {
        return gapi.auth2.getAuthInstance()
            .signIn({scope: "https://www.googleapis.com/auth/indexing"})
            .then(function() { console.log("Sign-in successful"); },
                  function(err) { console.error("Sign-in error", err); });
      }
      function loadClient() {
        gapi.client.setApiKey("zzzzzzzzzzzzzzzzz");
        return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
            .then(function() { console.log("GAPI client loaded for API"); },
                  function(err) { console.error("Error loading GAPI client for API", err); });
      }
      // Ensure that the client is loaded and sign-in is complete before using this method.
      function execute() {
        return gapi.client.indexing.urlNotifications.publish({
          "resource": {}
        })
            .then(function(response) {
                    // Manage the results here (response.result includes the parsed body).
                    console.log("Response", response);
                  },
                  function(err) { console.error("Execution error", err); });
      }
      gapi.load("client:auth2", function() {
        gapi.auth2.init({client_id: "samplezzzzzzzzzzzzzzzz.apps.googleusercontent.com"});
      });
    </script>
    <button onclick="loadClient().then(authenticate)">authorize and load</button>
    <button onclick="execute()">execute</button>

Error still occurs; error code: 400 message: "Request contains an invalid argument." status: "INVALID_ARGUMENT"

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

What causes the difference between object[key] and Object.key in JavaScript?

After running the following code snippet, I observed that "typeof object[key]" is displaying as a number while "typeof object.key" is showing undefined. Can anyone explain why this unusual behavior is occurring? var object = {a:3,b:4}; for (var key in o ...

Modifying the default text within a select box using jQuery

Within a select box identified as 'edit-field-service-line-tid', there is default text displayed as '-Any-'. This particular select field has been generated by Drupal. I am looking to use jQuery to change the text '-Any-' to ...

Utilizing Node.js for Lambda Functions

I am attempting to retrieve a list of all EC2 instances in a specific region using a lambda function. Below is the code snippet I am using: const AWS = require('aws-sdk'); AWS.config.region = '******'; exports.handler = async function( ...

Load the content of the dialog and transfer variables

After struggling for days, I am still unable to find a solution to my current dilemma. In my database, there are approximately 1300 items each with its own unique "id", a corresponding "name", and a property called "enabled". My goal is to display links t ...

Styling the border of elements with a data attribute set to "yes"

Managing a set of icons with customizable borders is the challenge I'm currently facing. The goal is to allow users to select up to 5 icons, with specific border colors assigned based on their selection order. The first selected icon should have a yel ...

Issue encountered when executing the migration fresh seed: SyntaxError, which indicates the absence of a closing parenthesis after the

Having trouble with a nextJS project that utilizes mikro-orm? Struggling to overcome this persistent error for days: C:\Users\BossTrails\Documents\core.nest-main_2\node_modules\.bin\mikro-orm:2 basedir=$(dirname "$(e ...

Animating cloned meshes in Three.js

I'm having an issue when trying to generate copies of a 3D json model that I've animated. Everything works fine with just one model in the scene. However, as soon as I attempt to create multiple copies, I encounter the following error: Uncaught ...

"Troubleshooting: Why is the 'RectAreaLightHelper' not moving correctly in React-three-fiber

Issue Overview: I have noticed that the rectAreaLight behaves differently compared to other light helpers in my project. Despite using the "useHelper" function and placing it in the "three/examples" folder, the position of the rectAreaLight does not change ...

Is there a way to create a menu using only CSS?

Is there a way to achieve this using only CSS without any JavaScript? For reference, here's the fiddle: http://jsfiddle.net/q646Ljg6/4/ This is the HTML: <div id="navigation" class="navigation"> <div id="dropmenu" class="dropmenu"> ...

Why does the loginStatus in Redux become undefined when the component is initially rendered?

Currently diving into Redux and encountering a problem that is new to me as I usually work with React without redux. The issue arises when I attempt to showcase a portion of my state within a component named loginStatus. Despite setting up the state in the ...

The loading bar animation doesn't begin at a blank slate

I'm currently working on a project that utilizes Django for the backend and Bootstrap for the frontend. I have to admit, I am quite inexperienced when it comes to front-end development; JavaScript seems like magic to me. One of the key features I nee ...

What is the Ideal Location for Storing the JSON file within an Angular Project?

I am trying to access the JSON file I have created, but encountering an issue with the source code that is reading the JSON file located in the node_modules directory. Despite placing the JSON file in a shared directory (at the same level as src), I keep r ...

Find the specific element that is visible within a customized viewport, such as a div or ul

Exploring the capabilities of the Viewport Selectors for jQuery plugin, here is a snippet of its source code: (function($) { $.belowthefold = function(element, settings) { var fold = $(window).height() + $(window).scrollTop(); return fold <= $ ...

The styling of Material UI (MUI) buttons is not displaying correctly

Why are my MUI button components displaying differently than the documentation? I have not made any external .css file or theme changes except for the ones listed. I have also installed the Roboto font and configured the typography. I want any changes I ma ...

The script for tracking cursor coordinates is incompatible with other JavaScript code

<html> <script language="javascript"> document.onmousemove=function(evt) { evt = (evt || event); document.getElementById('x').value = evt.clientX; document.getElementById('y').value = evt.clientY; document.ge ...

What is the best way to create a tooltip that appears when a user hovers over text within an <ins> tag?

Alright, I've defined a custom <ins> tag with the following CSS: ins{ color:blue; font-weight:500; text-decoration:none; } ins:hover{ cursor: pointer; cursor: hand; text-decoration:underline; } I'd like to add a ...

The interplay between React Bootstrap responsive design, React hooks, and Alan AI is not producing the desired results

As a newcomer to react hooks, I've only been using them for a few weeks now. I'm currently working with my react card component, which ideally should be divided into 3 columns in one row. However, they are stacking on top of each other vertically ...

What is the best way to extract a list of particular items from a nested array?

When I execute the following code: var url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=categories&titles=Victory_Tests&callback=?"; $.getJSON(url,function(data){ $.each(data, function(i, item) { console.lo ...

Is there a way to modify the default color when the header is assigned the "sticky" class?

Currently, I am in the process of building my own website and have implemented an exciting hover effect that randomly selects a color from an array and applies it when hovering over certain elements. However, once the cursor moves away, the color reverts b ...

Sequential execution of multiple useState updates when an update triggers a re-render

Can you explain why the function setPeople is being executed after setFirstName, setEmail, and after the event handler has been exited? const [firstName, setFirstName] = useState(''); const [email, setEmail] = useState(''); const [peopl ...