Josh
Josh

Reputation: 37

How do I pass a variable from one javascript file to another?

I'm trying to adapt the code in this github repo: Github repo for use on Google app engine, but I am having a problem passing a variable from /app.js to /books/crud.js. I've added google authentication to app.js, and so can access the user's email address within that file, but when I try to export that variable and access it in crud.js, it doesn't work. I've tried adding the variable to the export at the bottom of app.js, so that it reads:

module.exports = { app, email };

and then importing it in crud.js with the following statement:

const appFile = require('../app');

and passing the variable to a .pug file from crud.js with:

    router.get('/add', (req, res) => {
  res.render('books/form.pug', {
    book: {},
    action: 'Add',
    user: appFile.email
  });
});

This doesn't work however and the variable is not getting pulled through. Any help would be appreciated! Here is the full app.js file that I am using:

'use strict';

// [START getting_started_auth_all]
const express = require('express');
const metadata = require('gcp-metadata');
const {OAuth2Client} = require('google-auth-library');

const app = express();
const oAuth2Client = new OAuth2Client();

var user = "";

// Cache externally fetched information for future invocations
let aud;
// [START getting_started_auth_metadata]
async function audience() {
  if (!aud && (await metadata.isAvailable())) {
    let project_number = await metadata.project('numeric-project-id');
    let project_id = await metadata.project('project-id');

    aud = '/projects/' + project_number + '/apps/' + project_id;
  }

  return aud;
}
// [END getting_started_auth_metadata]

// [START getting_started_auth_audience]
async function validateAssertion(assertion) {
  if (!assertion) {
    return {};
  }

  // Check that the assertion's audience matches ours
  const aud = await audience();

  // Fetch the current certificates and verify the signature on the assertion
  // [START getting_started_auth_certs]
  const response = await oAuth2Client.getIapPublicKeys();
  // [END getting_started_auth_certs]
  const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync(
    assertion,
    response.pubkeys,
    aud,
    ['https://cloud.google.com/iap']
  );
  const payload = ticket.getPayload();

  // Return the two relevant pieces of information
  return {
    email: payload.email,
    sub: payload.sub,
  };
}
// [END getting_started_auth_audience]
//[START getting_started_auth_front_controller]
let email = 'None';

app.get('/', async (req, res) => {
 const assertion = req.header('X-Goog-IAP-JWT-Assertion');

 try {
   const info = await validateAssertion(assertion);
   email = info.email;
 } catch (error) {
   console.log(error);
  }

  res.status(200).send(`Hello ${email}`).end();
});

// [END getting_started_auth_front_controller]
app.set('views', require('path').join(__dirname, 'views'));
app.set('view engine', 'pug');

// Books
app.use('/books', require('./books/crud'));
app.use('/api/books', require('./books/api'));

// Redirect root to /books
app.get('/', (req, res) => {
  res.redirect('/books');
});

app.get('/errors', () => {
  throw new Error('Test exception');
});

app.get('/logs', (req, res) => {
  console.log('Hey, you triggered a custom log entry. Good job!');
  res.sendStatus(200);
});

// Start the server
const port = process.env.PORT || 8080;
app.listen(port, () => {
  console.log(`App listening on port ${port}`);
});
module.exports = {
  app,
  email
  };

Upvotes: 0

Views: 1037

Answers (1)

irfan_sifat
irfan_sifat

Reputation: 47

You can't pass a variable from one js file to another js file. But you can use variables from different js files by including an HTML/PHP file.

Let's you have two js files: one.js

x=10;

and two.js

y=2;

Now you have an index.html file

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

<script>
    console.log(x+y);
</script>

output in console is 12

Upvotes: 1

Related Questions