I am trying to send data to google apps script so that it will add that data onto a google slides presentation that will be created in the users google drive. I am using the OAuth2 library.
https://github.com/googleworkspace/apps-script-oauth2
I am sending a fetch request to my web app url (execute as user, accessible to anyone with google account). However I keep on getting a CORS error:
Access to fetch at ‘https://script.google.com/macros/s/AKfycbzCdWHQn3AOxBsICRFxVqJ8DBvNoqUGX47Z1_svLZ-SRWE706WzmcSq3hWFwVzuWCjm/exec’ from origin ‘http://localhost:10003’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
**Here is my code
**
async function sendData() {
const jsonData = [{
"subject": "The girl",
"predicate": "ran home"
},
{
"subject": "The cat",
"predicate": "wore a hat"
},
{
"subject": "The tree",
"predicate": "fell down"
}
];
try {
const response = await fetch(
'https://script.google.com/macros/s/AKfycbxFkvMAEey-UPOWSJSqMMQBqLS0hPcUkYQRLTKAOPLuC4k-DU28sS8pVeRFhyMwzGfs/exec', {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(jsonData),
credentials: "include" // Ensure credentials are included for cross-origin requests
});
const responseText = await response.text();
console.log("Data response:", responseText);
// Check if the response contains an HTML redirection link
if (responseText.includes('Authorize')) {
// Redirect to the authentication URL
const parser = new DOMParser();
const doc = parser.parseFromString(responseText, "text/html");
const redirectUrl = doc.querySelector("a").href;
window.location.href = redirectUrl;
return;
}
const data = JSON.parse(responseText);
console.log("Success:", data);
alert("Data sent successfully: " + JSON.stringify(data));
} catch (error) {
console.error("Error:", error);
alert("Error sending data: " + error.message);
}
}
**Here is my apps script code:
**
function doPost(e) {
Logger.log("doPost function ran");
var service = getOAuthService();
if (service.hasAccess()) {
Logger.log("User has access");
var accessToken = service.getAccessToken();
try {
Logger.log("acess Token: " + accessToken);
var response = UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files?maxResults=10', {
headers: {
Authorization: 'Bearer ' + accessToken
}
});
Logger.log("Drive API Response: " + response.getContentText());
var jsonData = JSON.parse(e.postData.contents);
var presentation = copyAndModifyPresentation(jsonData);
var url = presentation.getUrl();
Logger.log("Presentation URL: " + url);
return ContentService.createTextOutput(JSON.stringify({ message: 'Presentation created with URL: ' + url }))
.setMimeType(ContentService.MimeType.JSON);
} catch (err) {
Logger.log("Error: " + err.message);
return ContentService.createTextOutput(JSON.stringify({ error: 'Invalid JSON: ' + err.message }))
.setMimeType(ContentService.MimeType.JSON);
}
} else {
Logger.log("User does not have access. Need to authorize.");
var authorizationUrl = service.getAuthorizationUrl();
return ContentService.createTextOutput(JSON.stringify({ status: "unauthenticated", authUrl: authorizationUrl }))
.setMimeType(ContentService.MimeType.JSON);
}
}
Thank you
I have tried using no-cors but the data is only posted if the user is already signed into a google account. To prompt the user to sign in, I can’t have the mode set as no-cors, because I need a response which would contain the authorization URL.
I also tried setting up a PHP proxy server but it gives me a 401 error code
POST http://localhost:10003/wp-content/themes/twr/handle-google-auth.php 401 (Unauthorized)