The API for executing Apps Script returns an unauthenticated error

My application is encountering an issue with the Apps Script execution API, while other APIs are functioning properly. The error code 401 is being thrown with the message: "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential." I am using the same Google Cloud Project ID and have the Apps Script function API properly configured. The email sending API and Drive API are working fine, but this specific API is causing trouble. The application is running on localhost.

To troubleshoot, I will focus on the relevant parts of the code that might be causing the problem.

<script src="https://apis.google.com/js/platform.js?onload=onLoadCallback" async defer></script>

<script>
window.onLoadCallback = function(){
gapi.load('auth2', initSigninV2);
};

function initSigninV2() {
    gapi.auth2.init({
            apiKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
            discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest","https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest","https://script.googleapis.com/$discovery/rest?version=v1"],
            clientId: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com',
            scope: 'https://www.googleapis.com/auth/drive'+' https://www.googleapis.com/auth/gmail.send'+' https://www.googleapis.com/auth/script.scriptapp'
    }).then(function (authInstance) {
        if(!gapi.auth2.getAuthInstance().isSignedIn.get()) {
        gapi.auth2.getAuthInstance().signIn();

        }
                 // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());

    });
}

</script>

The function that is failing is:

function appScript(callback, data, field, dl) {
    var scriptId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    var request = {
        'function': 'doPost',
        'parameters': {'data':JSON.stringify(data)}
    };
    var headers = getClientRequestHeaders();
    console.log(headers);

    gapi.client.request({
        'root': 'https://script.googleapis.com',
        'path': 'v1/scripts/' + scriptId + ':run',
        'method': 'POST',
        'headers': headers,
        'body': request
    }).then(function (response) {
            console.log(response);
    //      callback(response.fileid, response.id, field);
    //      if (dl) {
    //      dl(response.fileid);
    //      }
        });
}

Answer №1

After some investigation, I discovered the answer: Code 401 was being triggered due to insufficient scopes. Upon reviewing my Google Apps Script and checking the Scopes settings under File > Properties, I identified the missing scope required for the operation.

Upon adding this missing scope, the script executed flawlessly.

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

Establish a connection to a regular socket by utilizing WebSocket technology

I am attempting to connect a client interface to a hardware device using WebSocket in a browser like Chrome. The code snippet I have been using for connection is as follows: var ws = new WebSocket("ws://127.0.0.1:13854"); ws.onopen = function() ... Howev ...

Tips for adding your artistic touch to photos

I'm currently facing a challenge in creating a chart that overlaps an image. The bars and text on the chart are displaying perfectly when I remove the background image. However, I'm struggling to get the bars and text to appear on top of the imag ...

Is there a way to utilize the function body onload in jQuery?

I have some code that needs to be fixed. Currently, when I see <body onload="start()" onresize="resize()" onorientationchange="resize()">, I want the following code snippet to work: $("button").click(function(){ $("body").onload = start; or win ...

Error: Trying to access the 'keyboard' property of an undefined object

I am encountering an error message 'Cannot read property 'keyboard' of undefined' and I'm not sure how to fix it. I just want to check if the keyboard is visible on the screen, but this specific line of code seems to be causing the ...

Disable Dates in Material UI Date Textfield

Is there a way to prevent users from selecting dates between the specified Min and Max dates in a material UI date textField? For example, if the minimum date is today's date 01/30/2023 and the maximum date is next month's date 02/30/2023, I wou ...

Encountering an issue with using third-party APIs due to receiving an error message stating that the requested resource does not have the 'Access-Control-Allow-Origin' header

My current challenge involves attempting to access a third-party API using AngularJS. Interestingly, I only encounter this issue in Chrome, as it works perfectly fine in IE. The error message that pops up reads as follows: XMLHttpRequest cannot load https ...

Is there a way to display a message in a div container instead of using the alert box when there is a successful ajax response?

Hey there, I'm currently working on implementing error validation handling for a custom form that I've created. I'm looking to display the error messages in a designated div rather than using the standard browser alert box. Since I'm fa ...

Combine two comma-separated strings in JavaScript to create an array of objects

I have two strings separated by commas that I want to transform into an array of objects. { "id": "1,2,3", "name": "test 1, test 2, test 3" } Is there a way to convert this into the desired object format? { &q ...

Automatically hide a label after a certain amount of time following a button click

Currently, I am working with ASP.NET and C#. Within my application, there is a registration form that includes a label to display the status of registration, either success or failure. The content of this label is determined dynamically in the codebehind ...

Trouble with Ajax transmitting multiple PHP variables

I am attempting to utilize an ajax request to visit a URL with two parameters. Unfortunately, my current script is not displaying any response. $(document).ready(function(){ $("#ocountClc").click(function (){ $.ajax({ type: "POST", url: "h ...

What is the process for executing a function if the Materialize.css autocomplete feature is not chosen?

Is it feasible to create a function that triggers only when a user does not select an option from Materialize.css autocomplete feature? My goal is to automatically populate an email field with a predefined value based on the user's selection in anothe ...

Troubleshooting the Google OAuth 2.0 SAMEORIGIN Issue

Trying to bypass the SAMEORIGIN error while using Google's JavaScript API is a timeless challenge. Here is an example of what I have tried: let clientId = 'CLIENT_ID'; let apiKey = 'API_KEY'; let scopes = 'https://www.google ...

Getting the Featured Image from a Post Link in Wordpress: A Step-by-Step Guide

For my Wordpress project, I have a group of links leading to inner pages, each with their own featured image. These links are created using the menu feature in Wordpress. My goal is to allow users to click on these links and have the featured image from t ...

Passing data received from a node.js request (using https.get) to a separate JavaScript file

I'm new to posting here, so my explanation might not be very clear. I am working on a project using node.js to fetch data and pass it to another js file for use in an html file. The structure of my app folder is as follows: -App -node_modules -publi ...

Utilizing an AngularJS service to communicate with a web API

Having trouble retrieving data from a web api and passing it back to a JavaScript file. I've tried using http://localhost:8584/api/Testing/5 to see if there are any results, but no luck so far. //This is the JavaScript controller that calls the serv ...

Unleashing the power of JavaScript: Sharing arrays and data structures effortlessly

Currently, I am utilizing HTML & JavaScript on the client side and NodeJs for the server side of my project. Incorporated in my form are multiple radio buttons. When the user clicks on the submit button, my intention is to post the results to the server. ...

JavaScript has the ability to manipulate the width of an element by using methods to both retrieve

I have a unique situation where I need to dynamically adjust the width of a ul list element based on the text content inside it. Specifically, I want the width of the ul list to be equal to the width of the first list item, which can change frequently. My ...

How come the action doesn't trigger in my React/Redux application?

Currently, I am in the process of developing a small application that incorporates modals. Instead of relying on pre-made packages like react-modal, I have taken the initiative to build the modal functionality from scratch. 1) Defining a reducer located i ...

I am having trouble with my jQuery login function not properly connecting to the PHP file

Hey there, I've been working on creating a login system from scratch by following an online tutorial. The initial Javascript is functioning properly as it detects errors when the inputs are empty. However, once I enter text into the input fields and c ...

challenges with managing memory during express file uploads

I'm experiencing memory problems with file uploads while hosting my site on NodeJitsu. When I try to upload files, my app crashes with this error message: { [Error: spawn ENOMEM] code: 'ENOMEM', errno: 'ENOMEM', syscall: 'spa ...