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