CORS error when sending POST request to google apps script (using client side javascript)

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
**

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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);
}
}
</code>
<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); } } </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:
**

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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);
}
}
</code>
<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); } } </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)

New contributor

ricekrispytreets is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật