0

I get a CORS error response when I tried to post my data to my Google Spreadsheet via a Web App. This is the error I get:

Access to XMLHttpRequest at 'myGoogleSpreadSheetApiURL' 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.

I did some solution, I searched on internet but I can't solve the issue... I could already get my JSON data from the Google Spreadsheet.

When I push my createButton, I can post and write my data on my Google Spreadsheet.

How should I fix my code ? Do you have any idea ?

This is my react.js code:

import React,{ Component } from 'react';
import Paper from '@material-ui/core/Paper';
import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:3000';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';

const api = 'https://myGoogleSpreadSheetApiUrl';



class  Price extends Component  {
  state = {
    info: []
  };
  
  constructor(){
    super()
    axios.get(api)
    .then((res) =>{
      console.log(res.data)
      this.setState({
        info: res.data
      })
    })
  };

  createInfo = () =>{
    let res = axios.post(api,{
      id: 100,
      product: "product100",
      price: 1000,
      miniLot: 1000,
    })
    console.log(res)
  }

render(){
      return (
        <div>
              <button onClick={this.createInfo}>createButon</button>
                <Paper>
                   {this.state.info.map(info => <p key={info.id}>{info.product}</p>)}
                </Paper>
        </div>
      );
    }
}

export default Price;

and this is my Google Apps Script code:

function getData(priceDB) {
  var sheet = SpreadsheetApp.getActive().getSheetByName(priceDB);
  var rows = sheet.getDataRange().getValues();
  var keys = rows.splice(0, 1)[0];
  return rows.map(function(row) {
    var obj = {};
    row.map(function(item, index) {
      obj[String(keys[index])] = String(item);
    });
    return obj;
  });
}

function doGet() {
  var data = getData('DBprice');
  return ContentService.createTextOutput(JSON.stringify(data, null, 2))
  .setMimeType(ContentService.MimeType.JSON);
}


function doPost(e) {
  
  var ss       = SpreadsheetApp.getActiveSpreadsheet();
  var sheet    = ss.getSheetByName('DBprice'); 
  var PostData = JSON.parse(e.postData.contents);
  
  sheet.appendRow([PostData.id, PostData.product, PostData.price]);
}
0

1 Answer 1

6

Only the following HTTP methods are supported by Google apps script web- application currently:

  • POST
  • GET

OPTIONS method is currently not supported. So, if requests from your React web-app is preflighted, the requests will fail(). To avoid preflighting, consider changing the post body and Content-Type to one of the following types(so called Simple requests):

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

Also, In order to avoid redirection to a html page, you should return text from the server side.

Client side:

axios.defaults.headers.post['Content-Type'] = 'text/plain';
/*....*/
createInfo = () =>{
 let res = axios.post(api,JSON.stringify({
  id: 100,
  product: "product100",
  price: 1000,
  miniLot: 1000,
  })
 )
//console.log(res)
}

Server side:

function doPost(e) {
  /*Stuff*/
  return ContentService.createTextOutput("done");
}
Sign up to request clarification or add additional context in comments.

6 Comments

I tried your solution, but it's still not working. Code: ``` try { axios.defaults.headers.post["Content-Type"] = "text/plain"; await axios .post( ${process.env.NEXT_PUBLIC_URL}?reqType=postData&admin=true&login=true&adminCode=${adminCode} ) .then(() => { console.log("success"); localStorage.setItem("admin", "true"); route.push("/"); }); } catch (error) { console.error(error); } ```
@kriptonian The term "not working" isn't descriptive enough for me to debug. Consider asking a new question with minimal reproducible example
@kriptonian Also try removing the query paramaters from the url and sending a body in post.
Tried that too but still it's giving cors error
In some deployment it's working fine and in some it's giving CORS error, I am really confused 😢
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.