How to handle CORS problems using Apps Scrips in React?

Viewed 64

I just want make my react send and receive data for a private sheets, using some credential for this if necessary, my project is a site with interesting forms for workers and my boss want see these answers in google sheets. I already tried this:

  1. Sheets API using Node Js, but i can't put Node in my project and dont know how to use this.
  2. Sheets API using JS on React but i take a lot of strange libraries to make the #1 work, not happen.
  3. Google Apps Script, my last one attempt, i make one function to take data, transform this data on JSON file and return that. All rigth with this, i guess, but when i try use this function on react a wild bug appears: CORS policy.

Error:

localhost/:1

Access to XMLHttpRequest at 'https://script.google.com/macros/s/AKfycbxuz7xwcOu77AqEsAnnOS0MeQ2qu5D47ZnGRhMS3su_OegiNeyyFdoY3cK3svybyBZb/exec' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My JS code:

const obj = {
    redirect: "follow",
    method: "POST",
    headers: {
        'Access-Control-Allow-Origin': '*',
        "Content-Type": "text/plain;charset=utf-8",
    },
};
const url = "https://script.google.com/macros/s/AKfycbxuz7xwcOu77AqEsAnnOS0MeQ2qu5D47ZnGRhMS3su_OegiNeyyFdoY3cK3svybyBZb/exec";
axios.get(url, obj)
    .then((response) => {
        console.log(response);});

My Apps Script code:

function doGet(e) {
  const ss = SpreadsheetApp.openById("1Qo78FwRfUBE20q3uJO4me-I30yd9IO64_cf48OER2Qk").getSheetByName("pag1");
  const values = ss.getDataRange().getValues();


  //Headers
  const headers = values[0];
  //Values
  const info = values.slice(1);


  const holder = [];
  info.forEach((ele, ind)=>{
    const temp = {};

    headers.forEach((header,index) =>{
      header = header.toLowerCase();
      temp[header] = ele[index];
    });

    holder.push(temp);
  });

    Logger.log(holder);

  const output = JSON.stringify({
    status: true,
    data: holder
  });

  return ContentService.createTextOutput(output).setMimeType(ContentService.MimeType.JSON);
}

Script dev link: https://script.googleusercontent.com/macros/echo?user_content_key=sznzc94eVNLBu3aIH1EF1AQzuKbRbFsIrDm9SpEcspMuOGcCWD0DQpYUFXf_-EDdOUBEToRFCd8Toi2pg73mnseCZUFc__HHm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnFFyHLiy6APruhip6byWAMZqTnK1bODOhKFDg3M9dJJF-C53vkZT1WCZ_kcKr-1V1Q&lib=MWvmhuupDFy3ZSGL-SCi1vYvpuuAzsMhg

If i put code:"no-cors" the res no have my data. What am i doing wrong?

1 Answers

install cors npm install cors --save

and just add these lines in your main file where your request is going.

const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
Related