如何解决阻止 Google Apps 脚本中 AJAX 请求的资源'MIME type mismatch error'?



我试图用Jquery.ajax而不是fetch来实现这里的代码。

当我进行AJAX调用时,我得到以下错误:

The resource from “https://script.googleusercontent.com/macros/echo?...” was blocked due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff).

谷歌应用程序脚本可以很好地使用cURL,所以我怀疑我的(非常简单的(GApps脚本和我的客户端脚本之间存在一些分歧。

这是GApps脚本:

function doGet(e) {
const id = e.parameter.spreadsheetId;
const sheetName = e.parameter.sheetName;
const sheet = SpreadsheetApp.openById(id).getSheetByName(sheetName);
const values = sheet.getDataRange().getValues();
return ContentService.createTextOutput(JSON.stringify({values: values})).setMimeType(ContentService.MimeType.JAVASCRIPT);
}

注意:我尝试将最后一行的MimeType更改为JSON,但没有成功。

以下是我在客户端脚本中调用的AJAX设置:

var settings = {
'cache': false,
'dataType': "jsonp",
'async': true,
'crossDomain': true,
'url': url,
'method': 'GET',
'headers': {
'accept': 'application/json',
'Access-Control-Allow-Origin': '*'
}
};

我在火狐浏览器工作。Chrome中也出现了类似的错误。我该如何解决此问题?

我相信你的目标如下。

  • 您希望使用jQuery.ajax()而不是fetch来请求Web应用程序

为此,当您的settings被修改时,下面的修改如何?

修改的脚本:

var settings = {
'url': url,
'method': 'GET',
'dataType':"json",
'data': {spreadsheetId: "###SpreadsheetId###", sheetName: "###SheetName###"},
};
示例脚本:
var url = 'https://script.google.com/macros/s/###/exec';
var settings = {
'url': url,
'method': 'GET',
'dataType':"json",
'data': {spreadsheetId: "###SpreadsheetId###", sheetName: "###SheetName###"},
};
$.ajax(settings).done(res => {
console.log(res.values);  // By this, you can retrieve the values of `{values: values}` from Web Apps.
}).fail(err => console.log(err));

注:

  • 当您修改Web应用程序的谷歌应用程序脚本时,请将Web应用程序重新部署为新版本。这样,最新的脚本就会反映到Web应用程序中。请小心
  • 在上面修改的脚本中,可以使用您的谷歌应用程序脚本
  • 在这种情况下,我可以确认上面的脚本适用于Chrome

参考:

  • jQuery.ajax((

最新更新