Google App Script Web App GET和POST请求被CORS政策阻止 [英] Google App Script Web App GET and POST request blocked by CORS policy

查看:115
本文介绍了Google App Script Web App GET和POST请求被CORS政策阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Google Web脚本应用程序,该应用程序将用户名和电子邮件添加到电子表格中.当直接从浏览器中访问网页时,此方法运行良好,但是来自网站的GET和POST请求均返回错误访问以' https://script.google.com/macros/s/AKfycbxkG5hM6MMswwHdzWSJKwutMYsOZRT3zjC7jFti0sDvJ47bWB4BTsHPhvbyEVGSsSc5/exec '从原点 '' 已被封锁的CORS政策:否' 接入控制 -"Allow-Origin"标头出现在所请求的资源上.如果不透明的响应满足了您的需求,请将请求的模式设置为"no-cors",以在禁用CORS的情况下获取资源."

I created a Google Web script app that adds a user's name and email to a spreadsheet. This works fine when accessing the web page from directly in the browser, but both GET and POST requests from a website returns the error "Access to fetch at 'https://script.google.com/macros/s/AKfycbxkG5hM6MMswwHdzWSJKwutMYsOZRT3zjC7jFti0sDvJ47bWB4BTsHPhvbyEVGSsSc5/exec' from origin '' 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."

我不一定需要POST请求的响应,但是使用'no-cors'并不能真正更新电子表格(我进行了测试,以确保它在网站之外有效)

I don't necessarily need a response from the POST request, but using 'no-cors' doesn't actually update the spreadsheet (I tested to make sure it worked outside of website)

我已经使用了XMLHttpRequest和fetch方法,同时使用了GET和POST请求,并更改了各种设置以尝试使其正常工作,但到目前为止还算不上成功.

I've used both XMLHttpRequest and the fetch method, with both GET and POST requests and a variety of the settings changed to try to get this to work but no luck so far.

我试图修改Google Apps脚本项目中的设置(设置为以我的身份执行,任何人甚至都可以访问匿名设置)和清单(此处没有很多,

I've tried to modify settings in the Google Apps Script Project (Set to execute as me, anyone can access even anonymous) and the manifest (not much here, documentation reference).

我查看了这些堆栈溢出帖子以寻求帮助,但是它们的解决方案对我而言不起作用(任何解决方案均不适用于我的情况)

I've looked at these stack overflow posts to try to help, but their solution didn't work for me (any didn't exactly apply to my situation)

App Script发送405响应尝试发送POST请求时

Google Apps脚本跨域请求已停止

这是我的提取方法(最近一次尝试)

Here's my fetch method (most recent attempt)

fetch("https://script.google.com/macros/s/AKfycbxkG5hM6MMswwHdzWSJKwutMYsOZRT3zjC7jFti0sDvJ47bWB4BTsHPhvbyEVGSsSc5/exec", {
    method: 'POST',
    data: data,
    mode: 'cors',
    credentials: 'include', // include, *same-origin, omit
    redirect: 'follow',
    headers: {
        'Content-Type': 'text/plain;charset=utf-8',
    }
}).then(response => {
    console.log("success:", response);
});

现在服务器应该返回一个字符串"Success",但是我得到了前面提到的错误.

Right now the server should return a string that says "Success" but instead I get the error I mentioned before.

修改我忘了在Google App脚本中包含doGet和doPost方法:

Edit I forgot to include the doGet and doPost methods on the Google App Script:


var emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

function doPost (e){
  if(!e) return ContentService.createTextOutput("No e");
  if(!e.parameters) return ContentService.createTextOutput("No params");
  if(!e.parameters.email) return ContentService.createTextOutput("No email");
  if(!e.parameters.name) return ContentService.createTextOutput("No name");
  if(!emailRegex.test(e.parameters.email)) return ContentService.createTextOutput("Wrong email format"); // if the email is not in proper format, return

  return addToDoc(e.parameters);
}

function doGet (e){

  if(!e) return ContentService.createTextOutput("No e");
  if(!e.parameters) return ContentService.createTextOutput("No params");
  if(!e.parameters.email) return ContentService.createTextOutput("No email");
  if(!e.parameters.name) return ContentService.createTextOutput("No name");
  if(!emailRegex.test(e.parameters.email)) return ContentService.createTextOutput("Wrong email format"); // if the email is not in proper format, return

  return addToDoc(e.parameters);
}

function addToDoc (params){
  var email = params.email;
  var name = params.name;

  var sheet = SpreadsheetApp.openById("1X0sUNSFcv-phGbGy7jeo9K5WLEX5cxyh_1_X6kSPjPs").getSheets()[0];

  var dataRange = sheet.getDataRange();
  var values = dataRange.getValues();

  // If we already have the email in the system, return
  for(var x = 0; x < values.length; x++){
    for(var y = 0; y < values[x].length; y++){
      if(values[x][y].indexOf(email) > -1) return ContentService.createTextOutput("Already have email");
    }
  }

  // Gets current row index and updates
  var scriptProps = PropertiesService.getScriptProperties();
  var nextDataIndex = parseInt(scriptProps.getProperty("NEXT_DATA_INDEX"));
  scriptProps.setProperty("NEXT_DATA_INDEX", ""+(nextDataIndex+1));

  var insertRange = sheet.getRange(nextDataIndex, 1, 1, 2);
  insertRange.setValues([[name, email]]);

  return ContentService.createTextOutput("Success");
}


解决方案

所以事实证明我的doPost请求失败了(doGet正在工作),因为我使用的是 e.parameters 而不是 e.postData .当我收到错误消息时,我认为这是我的网站而不是Web应用程序出现的问题.


Solution

So it turns out my doPost request was failing (doGet was working) because I was using e.parameters and not e.postData. When I got the error message I assumed it was a problem with my website, not the web app.

谢谢您!我将永远花时间去修复网站

Thank you Tanaike! I would've spent forever trying to fix the website

推荐答案

尽管从您的问题来看我不确定您的Web Apps的Google Apps脚本,但此修改如何?

Although I'm not sure about your Google Apps Script of Web Apps from your question, how about this modification?

  1. 我认为您的Web应用程序可能不返回任何值.您可以将 return ContentService.createTextOutput()放在 doPost() doGet()的函数中.这样,在Google Apps脚本中,返回状态200.

  1. I think that your Web Apps might return no values. You can put return ContentService.createTextOutput() in the functions of doPost() and doGet(). By this, at Google Apps Script, the status 200 is returned.

function doPost(e) { // or doGet(e)

  // do something

  return ContentService.createTextOutput(); // Please add this.
}

  • 您可以按如下所示修改客户端脚本:

  • You can modify the client-side script as follows:

    fetch("https://script.google.com/macros/s/AKfycbxkG5hM6MMswwHdzWSJKwutMYsOZRT3zjC7jFti0sDvJ47bWB4BTsHPhvbyEVGSsSc5/exec", {
        method: 'POST',
        body: data,
        headers: {
            'Content-Type': 'text/plain;charset=utf-8',
        }
    }).then(response => {
        console.log("success:", response);
    }).catch(err => {
        console.log("Error:" + err);
    });
    

  • 注意:

    • 修改了Web Apps的Google Apps脚本后,请将该Web Apps部署为新版本.这样,最新脚本将反映到Web Apps.请注意这一点.
    • 如果我误解了您的问题,而这不是您想要的结果,我深表歉意.

      If I misunderstood your question and this was not the result you want, I apologize.

      这篇关于Google App Script Web App GET和POST请求被CORS政策阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆