Home > Software engineering >  How can import a global variable into another file?
How can import a global variable into another file?

Time:01-31

I am trying to use a global accessToken variable within another file but I keep getting the error Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Taat\Documents\Backend\server\controllers\authController' imported from C:\Users\Taat\Documents\Backend\server\controllers\dataController.js code: 'ERR_MODULE_NOT_FOUND'

where I am exporting it within authController and importing it within dataController as you can see below in the code:

authController.js:

export let accecssToken;

// rest of my code

dataController.js:

import { accecssToken } from "./authController";
export async function getActivityId(req, res) {
  const data = await getDataPromise();
  const activityIds = {};
  for (let i = 0; i < data.length(); i  ) {
    activityIds[data[i].id] = []; 
  }
  return res.json(activityIds);
}

export async function getDataPromise() {
  const link = `api/?access_token=${accecssToken}`;
  console.log("Link = ", link);
  const response = await axios.get(link);

  return response.data;
}

I do not see what I am doing wrong here can anyone spot it? Both files are in the same directory as you can see from the error messages paths

CodePudding user response:

Just add extension of exported file

import { accecssToken } from "./authController.js";

or You can use

const { accecssToken } = require('./authController');

CodePudding user response:

Use -

const {accessToken} = require("./authController");

Though seeing the naming convention and your code you're utilizing the accessToken, I would not recommend adding SECERTS in js files as it could be compromised.

Make a .env file at the root folder and add all secrets inside.

.env file should look like -

enter image description here

To use any .env variable, add

require("dotenv").config();

and then use -

const link = `api/?access_token=${process.env.ACCESS_TOKEN}`
  • Related