An unforeseen issue occurred with UrlFetchApp.fetch while using basic authentication in Google Apps Script

I am currently using Google Apps Script to fetch CSV data from a webpage using basic authentication and insert it into a spreadsheet. Below is the code snippet I am working with:

CSVImport.gs

function parseCSVtoSheet(sheetName, url)
{
  // Credentials
  var username = "myusername";
  var password = "mypassword";
  var header = "Basic " + Utilities.base64Encode(username + ":" + password);
  
  // Setting the authorization header for basic HTTP authentication
  var options = {
    "headers": {
      "Authorization": header
    }
  };
  
  // Getting the ID of the sheet with the name passed as parameter
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getSheetByName(sheetName);
  var sheetId = sheet.getSheetId();
  
  // Fetching the CSV data and inserting it into the spreadsheet
  var csvContent = UrlFetchApp.fetch(url, options).getContentText();
  var resource = {requests: [{pasteData: {data: csvContent, coordinate: {sheetId: sheetId}, delimiter: ","}}]};
  Sheets.Spreadsheets.batchUpdate(resource, spreadsheet.getId());
}

Lately, I have been experiencing an issue where sporadically I receive this error on the line that contains UrlFetchApp.fetch:

Exception: Unexpected error: http://www.myurl.com/data/myfile.csv (line 21, file "CSVImport")

I have attempted the following troubleshooting steps:

  • Embedding the credentials directly in the URL instead of using an Authorization header (which resulted in a different error message stating "Login information disallowed").
  • Encoding the credentials to base64 when passing them into the headers object (this approach did not resolve the issue).
  • Removing authentication entirely (resulted in a 401 response from the HTTP page).

It is puzzling why this problem has suddenly emerged and I am unsure about what other techniques to try. Any guidance would be greatly appreciated.

Answer №1

There is a newly discovered bug in the system, please check out this link

A large number of users have been impacted by this issue, so I suggest you "star" it to help bring attention to the problem and potentially speed up the resolution process.

Answer №2

I encountered a similar situation where I discovered that using the built-in function of Google Spreadsheet allowed me to retrieve values from a URL. To work around this issue, I followed these steps:

  1. Enter the formula =IMPORTDATA(URL).
  2. Retrieve the values from the sheet.

If you apply the above steps to your URL like

http://www.myurl.com/data/myfile.csv
, it should look like below.

Basic authorization for URL:

Upon reviewing your script, I noticed that basic authorization is being used. In such cases, you can include the username and password in the URL like

http://username:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbcbdac8c8ccd4c9dffbcccccc95d6c2cec9d795d8d4d6">[email protected]</a>/data/myfile.csv
.

Assuming your username is myusername and password is

mypassword</code, the URL would be <code>http://myusername:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f69b8f8697858581998492b6818181d89b8f83849ad895999b">[email protected]</a>/data/myfile.csv
.

One crucial point to note is that if your username or password contains specific characters, remember to encode them in the URL.

Sample script:

function myFunction() {
  const url = "http://myusername:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b8aca5b4a6a6a2baa7b195a2a2a2fbb8aca0a7b9fbb6bab8">[email protected]</a>/data/myfile.csv";  // Use your own URL.

  // Retrieve values from URL.
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getSheetByName(sheetName);
  sheet.clear();
  var range = sheet.getRange("A1");
  range.setFormula(`=IMPORTDATA("${url}")`);
  
  // Retrieve values from sheet into an array.
  SpreadsheetApp.flush();
  var values = sheet.getDataRange().getValues();
  range.clear();
  console.log(values)
}
  • When running the above script, the values from the URL will appear on the sheet as a two-dimensional array under values. If you wish to remove the formulas and keep only the values, copying and pasting may suffice.
  • In this solution, I utilized IMPORTDATA, but depending on your requirements, there may be more suitable functions available. Be sure to explore them accordingly.

Note:

  • This workaround is temporary. Once the underlying issue is resolved, you should revert to your original script.

References:

Answer №3

Turn off the Chrome V8 Runtime Engine until Google addresses the issue.

To turn off: Navigate to the Menu and select Run > Disable the new Apps Script runtime powered by Chrome V8

Answer №4

In reference to issue #346 on the official bug tracker here

Hey everyone, I stumbled upon a potential solution that has been effective for me. Try using empty brackets like this:

UrlFetchApp.fetch(apiLink, {});

This method worked perfectly for me.

I gave it a try and indeed, it solved the problem for me as well. It even works with the "new Apps Script runtime powered by Chrome V8."

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving data from a directive in an HTML table

Utilizing AngularJS, I am seeking a method to retrieve the value from an input located within a specific row in a table. Presented below is an input element. Upon clicking the "add" button, my objective is to extract the value corresponding to that partic ...

The functionality to show the login status is currently malfunctioning

I have a login status indicator section on my homepage which is connected to an ajax-php database. The login button performs two actions when clicked. <input value="Login" type="button" onclick='logInUser(/*function to handle login request*/);upda ...

Remove the final 5 characters from the HTML text

Below is the code block that I am unable to modify: <div class="parent"> <div class="wrap"> <span class="content">2026-01-31-08:00</span> </div> <div class="wrap" ...

What is the best way to manage a vuex dispatch response?

Despite feeling like the answer is right in front of me, I'm waving the white flag and seeking suggestions. The challenge lies in my login form that submits to an AWS API and reacts to the result. The trouble starts when the handleSubmit method is tr ...

Switching hamburger menu icons in Vue.js

I am trying to change a hamburger menu icon in my header to a cross icon when it is clicked. I have created a function in the computed property of my Vue template, but I'm not entirely sure about the implementation. How can I achieve this? Below is t ...

Use an EditText to capture user input, then pass the variables to a Webview by executing a javascript command

I'm currently working on a basic web application that aims to streamline the user experience by eliminating the need for repeated credential input upon website access (without saving passwords). After some exploration, I was able to identify and manip ...

Is it necessary to utilize process.env in node.js?

In my project, there is a .env file containing the following: ABC='abc' While in my app.js I can access the value abc using process.env.ABC, how can I require it to be used in my models' files? Attempting to use process.env.ABC in my model ...

Tips for creating query requests in ExpressJS

Can someone provide the correct command to write in an ExpressJS file in order to expose a single HTTP endpoint (/api/search?symbol=$symbol&period=$period)? Here is what's currently working: app.get('/api/search/', (req, res) => ...

Retrieving Time Format from JSON Within an Angular.js Application

Whenever I receive app data through an API in JSON format, the time stamps always come back looking less than desirable. They appear like this: 2013-11-25T12:44:02 In my Angular app, I haven't found a straightforward way to format these time stamp ...

Create a mechanism in the API to ensure that only positive values greater than or equal to 0 are accepted

My goal is to process the API result and filter out any values less than 0. I've attempted to implement this feature, but so far without success: private handleChart(data: Object): void { const series = []; for (const [key, value] of Object.e ...

transfer information between different express middleware functions within a universal react application

I am working on an isomorphic react app and I am looking for a way to pass state between express middleware functions. One of my express routes handles form submission: export const createPaymentHandler = async (req: Request, res: Response, next: NextFun ...

Click on the button to create a link and then seamlessly navigate there using a combination of ajax, php, and javascript

I am in need of a button that can trigger a php page through ajax. The purpose of this button is to open the client's email with a mailto link. The php page created generates an email containing an encrypted string that carries credentials for access ...

Having difficulty executing JavaScript code from the VB code behind

Recently, I have encountered a strange issue while working with ASP/VB.net. In my code behind VB file, I am trying to call a JavaScript function, but it seems like nothing is happening. Surprisingly, I have used a very similar method on several other pages ...

How can I retrieve the identifier in Socket.io?

Is there a way to retrieve the unique Id from the server using socket.io? I attempted using clients[socket.id] = socket; However, I encountered an error stating: connections property is deprecated. use getconnections() method Does anyone have any sugg ...

Ways to transmit data multiple times within a single request

I'm currently developing an app using Nodejs and express, where orders can be placed for specific products. In this application, when an order is received, it is saved in the database and a PDF receipt is generated immediately. However, since generati ...

Jump to Anchor when Page Reloads

Hey there! I'm currently developing a gallery script and I'm trying to figure out how to automatically position the page to the top of a specific anchor when it is loaded. I attempted to use the following code: <script>location.href = "#tr ...

Trouble with Vue: Sibling components unable to communicate

I am encountering an issue while trying to pass data from typing.js to ending-page.js within sibling components. Despite my efforts, the emit and event hubs are not functioning as expected. However, emitting from typing.js to the parent component works sea ...

Add the variable's value to the input field

It is necessary for me to concatenate a numeric value, stored in a variable, with the input fields. For example: var number = 5; var text = $("#dropdown_id").val(); I wish to append the value of the variable 'number' to 'dropdown_id' ...

What is the best way to integrate HTML code within a JavaScript function?

I need the HTML code to execute only when a specific condition in JavaScript is met. Here is the JavaScript code: <script type="text/javascript"> $(document).ready(function () { if(window.location.href.indexOf("index.php") > -1) { ...

Utilizing ReadableStream as a body for mocking the HTTP backend in unit testing for Angular 2

Looking to simulate the http backend following this helpful guide. This is my progress so far: Test scenario below describe('DataService', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ ...