Skip to content Skip to sidebar Skip to footer

How To Export A Variable Which Is In A Class In Nodejs

This is my file loginHandler.js class LoginHandler { merchantId = ''; returnURLForIframe(req, res) { merchantId = req.params.merchantId; } } module.exports = new

Solution 1:

I solved it by adding it to an environment variable on loginHandler.js

process.env.MERCHANT_ID = req.params.merchantId

and then on responseHandler.js, I accessed that variable

merchantId : process.env.MERCHANT_ID


Solution 2:

My loginhanderler.js

class LoginHandler {
  merchantId = '';
  returnURLForIframe(req, res) {
    this.merchantId = req.params.merchantId;
  }
}

module.exports = new LoginHandler();

My index.js

let loginHandler = require('./loginhandler');

let req = {
  params: {
    merchantId: 'a test',
  },
};

loginHandler.returnURLForIframe(req);

console.log(loginHandler.merchantId);

Solution 3:

You can define it as an object key

class LoginHandler {
  constructor() {
    this.merchantId = '';     
  }

    returnURLForIframe(req, res) {
      this.merchantId = req.params.merchantId;
    }  
}

Solution 4:

new LoginHandler

class LoginHandler {
    merchantId = "";
  returnURLForIframe(req, res) {
    this.merchantId = req.params.merchantId;
  }
}

module.exports = new LoginHandler();

FOR FUTURE REFERENCE (also for myself)

It was confusing to detect what the error was, so for me it was helpful to change the name of the variable:

class LoginHandler {
    other= "";
  returnURLForIframe(req, res) {
    other = req.params.merchantId;
  }
}

module.exports = new LoginHandler();

Then I saw that the error was ReferenceError: other is not defined and could solve it.

Also, besides logging, it was needed to call returnURLForIframe to see the error

const loginHandler = require("./loginHandler");
class ResponseHandler {
  getResponseFromCOMM(options, token, res) {
    loginHandler.returnURLForIframe({ params: { merchantId: "lalala" } });
    console.log(loginHandler);
  }
}
let rh = new ResponseHandler();
rh.getResponseFromCOMM("foo", "bar", "baz");

Post a Comment for "How To Export A Variable Which Is In A Class In Nodejs"