I created function in Google Apps Script, that works well when I run it in Google Apps Script. Output data returns to Google Sheets.
function testFunction11(
UrlFetchApp.fetch() is run from a button on Spreadsheet, X-Forwarded-For is automatically added to the header.X-Forwarded-For to the header, the error of An error has occurred. occurs.X-Forwarded-For is not used in the header, no error occurs.If my understanding is correct, how about this workaround? I think that there might be several workarounds. So please think of this as just one of them. In this workaround, Web Apps is used as a wrapper function.
At first, please copy and paste the following script. And please set testFunction11() to the button. When testFunction11() is run, testFunction11() requests to Web Apps (doGet()), and Web Apps requests to https://api.apiservice.com/api/v1/xxx?fields=somefields. By this, X-Forwarded-For is not used to the header of request. Then, the result of Web Apps is returned and put the value to the spreadsheet. Please deploy Web Apps, before you run the script.
function testFunction11() {
var rng = SpreadsheetApp.getActiveRange();
var url = ScriptApp.getService().getUrl();
var params = {method: "get", headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText());
rng.setValue(res);
}
function doGet() {
var url = "https://api.apiservice.com/api/v1/xxx?fields=somefields";
var encodedAuthInformation = Utilities.base64Encode("username:key");
var headers = {"Authorization" : "Basic " + encodedAuthInformation};
var params = {
'method': 'GET',
'muteHttpExceptions': true,
'headers': headers
};
var res = UrlFetchApp.fetch(url, params);
return ContentService.createTextOutput(res.getContentText());
}
Before you run this script, please deploy Web Apps.
For future searches on this topic: I had an issue with the exact same error message, where I was using UrlFetchApp#getRequest as a utility to generate a request object, then sending it with UrlFetchApp#fetchAll.
The solution was to avoid using getRequest and instead build the request by myself without using any X-Forwarded-For header, which allowed the request to complete successfully.
I can't find any documentation to support this, but I would speculate that the following issue occurred: when Google injects the X-Forwarded-For header before making a request, the IP it injects depends on the context the script gets executed in. I think Google validates that if that header is set manually, then the IP address needs to match either their GAS proxy's IP or the user's browser IP; which one to use seems to change depending on the context the script is executed in.