我正在从工作表数据中获取JSON 使用部署的应用程序脚本

浏览器中的JSON数据看起来正确

但是,当我将URL添加到一个名为www.example.com的应用程序中,

https://script.google.com/macros/s/AKfycbymN0Wkfl-Lp4n0kD2L1DXmY4BbZhi8CvoB8nW2pguvelXhqAhRo4YQuYquS5Mv_FU/exec?id=12ygFGlEbqosGDj_4VSg6pzTjnHn58XuLAtmMpkdoUzM&sheet=Elements&header=1&startRow=2

我收到CORS错误消息

Please make sure the url below is valid and CORS is enabled.

如何为这个部署的脚本启用CORS?

谢谢

Google表单数据和代码 https://docs.google.com/spreadsheets/d/12ygFGlEbqosGDj_4VSg6pzTjnHn58XuLAtmMpkdoUzM/edit?usp=sharing

应用程序脚本

/**
 * Test the original functionality of returning all objects
 * in the spreadsheet in JSON.
 */
function test1() {
  return runTest_({
      parameters : {
        id : "12ygFGlEbqosGDj_4VSg6pzTjnHn58XuLAtmMpkdoUzM",
        sheet : "Elements",
        header : 1,
        startRow : 2,
      }
  });
}

/**
 * Basic test logs a request and response. Use View -> Logs to check if it's
 * correct.
 * (In the future maybe actually check equality to expected output.)
 * @param request The HTTP request to test
 */
function runTest_(request) {
  console.log(request);
  console.log(doGet(request).getContent().toString());
}

/**
 * Main method is called when the script receives a GET request.
 * Receives the request, generates and returns the output.
 */
function doGet(request) {
  // Get request params.
  var sheetKey  = request.parameters.id;
  var sheetName = request.parameters.sheet;
  var callback  = request.parameters.callback;
  var headerRow = request.parameters.header;
  var startRow  = request.parameters.startRow;
    
  // Parse the spreadsheet.
  var spreadsheet = SpreadsheetApp.openById(sheetKey);
  var keys = getHeaderRowKeys_(spreadsheet, sheetName, headerRow);
  var data = readData_(spreadsheet, sheetName, keys, startRow);
  
  // Filter for matching terms.
  data = data.filter(function(entry) {
    var matches = true;
    for (var k in keys) {
      var key = keys[k].replace(/\s+/g, '_');
      var searchTerm = request.parameters[key];
      // Use the string form of the value since params are strings by default
      if (searchTerm != undefined)
        matches = matches && ("" + entry[key] == searchTerm);
    }
    // Matches is true iff all params are undefined or all values for keys match.
    return matches;
  });
  
  // Write and return the response.
  var response = JSON.stringify({ elements: data });
  var output = ContentService.createTextOutput();
  if (callback == undefined) {
    // Serve as JSON
    output.setContent(response).setMimeType(ContentService.MimeType.JSON);
  } else {
    // Serve as JSONP
    output.setContent(callback + "(" + response + ")")
        .setMimeType(ContentService.MimeType.JAVASCRIPT);
  }
  return output;
}

/**
 * Get a row in a spreadsheet as an Object, using the values in the header row as
 * keys and the corresponding row values as the values.
 * 
 * @param spreadsheet Spreadsheet object housing the sheet and header
 * @param sheetName Name of the specific sheet in the spreadsheet with the data
 * @param properties Optional array of keys to use for the row values. Default is the first row.
 * @param startRowNum Optional top row number of the rows to parse. The default is
 * the second row (i.e., below the header).
 */
function readData_(spreadsheet, sheetName, properties, startRowNum) {
  if (typeof properties == "undefined") {
    properties = getHeaderRowKeys_(spreadsheet, sheetName);
  }
  
  var rows = getDataRows_(spreadsheet, sheetName, startRowNum);
  var data = [];
  for (var r = 0, l = rows.length-1; r < l; r++) {
    var row = rows[r];
    var record = {};
    for (var p in properties) {
      record[properties[p]] = row[p];
    }
    data.push(record);
  }
  return data;
}

/**
 * Parse spreadsheet data as an array of Javascript Objects.
 *
 * @param spreadsheet Spreadsheet object with the data to get
 * @param sheetName Name of the specific sheet in the spreadsheet with the data
 * @param startRowNum Optional top row number of the rows to parse. The default is
 * the second row (i.e., below the header).
 */
function getDataRows_(spreadsheet, sheetName, startRowNum) {
  if (typeof startRowNum == "undefined") startRowNum = 2;
  
  var sheet = spreadsheet.getSheetByName(sheetName);
  return sheet.getRange(startRowNum, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
}

/**
 * Return the array of keys used in the header, replacing whitespace with underscores.
 * 
 * @param spreadsheet Spreadsheet object housing the sheet and header
 * @param sheetName Name of the specific sheet in the spreadsheet whose header values to get
 * @param rowNum Optional exact row number of the header. Default is the first row.
 */
function getHeaderRowKeys_(spreadsheet, sheetName, rowNum) {
  if (typeof rowNum == "undefined") rowNum = 1;
  return getHeaderRow_(spreadsheet, sheetName, rowNum).map(function(value) { 
    return value.replace(/\s+/g, '_');
  });
}

/**
 * Get the values in the header row of the given sheet in a spreadsheet
 * 
 * @param spreadsheet Spreadsheet object housing the sheet and header
 * @param sheetName Name of the specific sheet in the spreadsheet whose header values to get
 * @param rowNum Exact row number of the header.
 */
function getHeaderRow_(spreadsheet, sheetName, rowNum) {
  var sheet = spreadsheet.getSheetByName(sheetName);
  return sheet.getRange(rowNum, 1, 1, sheet.getLastColumn()).getValues()[0];
}

推荐答案

这只是我的猜测从你接下来的情况来看,

浏览器中的JSON数据看起来正确 但是,当我将URL添加到一个名为www.example.com的应用程序中, 我收到CORS错误消息

而且,从我访问你的Web应用程序的显示URL的结果来看,

我猜您当前问题的原因可能是由于Web应用程序的设置.因此,当我看到您提供的Electron 表格的Google Apps Script项目时,我注意到您的Web Apps的设置如下.

  "webapp": {
    "executeAs": "USER_ACCESSING",
    "access": "ANYONE"
  }

在这种情况下,为了访问Web应用程序,它需要登录到Google帐户.虽然我不确定But when I add the URL to an app called Kumu.io to visually represent the data中的Kumu.io,我想这可能是你当前问题的原因.

在这种情况下,请通过以下设置更新Web应用程序.

Execute as: me
Who has access to the app: Anyone

如果您想修改appsscript.json,请按以下方式修改.

  •   "webapp": {
        "executeAs": "USER_ACCESSING",
        "access": "ANYONE"
      }
    
  •   "webapp": {
        "executeAs": "USER_DEPLOYING",
        "access": "ANYONE_ANONYMOUS"
      }
    

通过此修改,无需登录Google帐户即可访问Web Apps.

注:

参考资料:

Json相关问答推荐

Azure Devops Pipeline:SON字符串变量丢失所有双引号

PowerShell脚本-替换json数组(转义$var将被视为不带双引号的文本)

您可以使用Jolt对JSON执行OR条件吗

带有PowerShell内核的NewtonSoft json.Net的奇怪行为

与错误相关的未定义&Quot;不是有效的JSON

使用Kotlin限制序列化类属性的允许整数值

Python 将 struct 化文本转换和筛选为对象

如何使用jolt规范将一个对象添加到另一个对象中并删除该对象

在 NX 工作区中跨多个应用共享 ngx-translate 翻译文件

golang递归json来构造?

使用带有逗号的字段名称构建 struct

如果 jq 数组中的字符串是对象或字符串,则获取值

如何将动态复杂 json 解析为dart 对象或模型

使用 jq 将键值行转换为 json

JBuilder中未定义的局部变量或方法json

ASP.NET MVC:使用 JsonResult 控制属性名称的序列化

如何将有向无环图 (DAG) 存储为 JSON?

如何在 Java 中将 YAML 转换为 JSON?

MVC JsonResult camelCase 序列化

将 JsonArray 添加到 JsonObject