0

Newbie coder here. By cobbling together tutorials, I created a .js module that uses Google's API to return the value of a cell in my Google Sheet.

The module, sheetsReader.js includes these two require lines at the top:

const {google} = require('googleapis');
let privatekey = require('../../config/privatekey.json');

And it defines a function, getCell(), that returns the value of whatever cell is passed to it as the argument—e.g. getCell('A6')

It works perfectly when I run it in node terminal. But I want to access this function in my index.html, so I can display a cell value on the page. (I'm aware there may be better ways to accomplish this, but I'm trying to plug this spreadsheet data into an existing page.)

To export the function, in sheetsReader.js, I have:

module.exports.getCell = getCell;

And to import in index.html I put in the header:

<script> 
import * as getCell from './js/sheetsReader.js' 
</script>

However, when I open the page, it fails to load properly because:

Uncaught ReferenceError: require is not defined at sheetsReader.js:1

I know now that require() does not work browser-side. I've tried to solve by using browserify, requirejs, and all sorts of other fixes, but none seem to work for an html page.

I feel like I'm probably missing something very fundamental here—so I apologize! I learned to set up a server just so I could use the Google API to read a spreadsheet... but no matter how I try I just can't seem to find a way to call the function I built!

Arlo
  • 31
  • 3
  • As an update: I got this to work by having `server.js` require `sheetsReader.js`, and then having my `index.html` make a series of GET requests to the server. No need for `require()` in the browser. This seems like a pretty inefficient way to accomplish a simple task—the browser makes one request at a time to the server, which passer the request to the module, and then the contents of each cell are returned to a local array—but it's the only solution I could figure out! @jfriend00 you're right about the what problem to be solved was. Curious what a better way would have been! – Arlo Oct 24 '20 at 05:50

1 Answers1

0

You are importing the google api value incorrectly you need to format it as

       const google = require('googleapis.js');
swift gaming
  • 142
  • 4
  • There is no `require()` in the browser so that's the more fundamental problem to be solved here. – jfriend00 Sep 23 '20 at 02:26
  • Thanks, @swift-gaming, but that doesn't actually seem to be the case. I originally used your proposed formatting, but it didn't work until I added {}—see this explanation: (https://stackoverflow.com/questions/49424721/why-using-var-google-instead-of-var-google-in-google-auth-oauth). Once I added the brackets, the js file worked fine when run in node. As jfriend00 said, the fundamental problem is with importing into the browser a function that relies on require(). – Arlo Sep 23 '20 at 16:23