Nehal Jaisalmeria
Nehal Jaisalmeria

Reputation: 432

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 LoginHandler();

I want to access the variable merchantId on another file

const loginHandler  = require('./loginHandler')
class ResponseHandler {
    
    getResponseFromCOMM(options,token, res){
        console.log(loginHandler.merchantId)
    }
}

But merchantId is undefined. Can you please tell me what I am doing wrong?

Here you can see the code on Glitch = https://glitch.com/edit/#!/turquoise-spiky-chrysanthemum

Upvotes: 0

Views: 463

Answers (4)

Nehal Jaisalmeria
Nehal Jaisalmeria

Reputation: 432

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

Upvotes: 2

malarres
malarres

Reputation: 2946

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");

Upvotes: 0

Sarath P S
Sarath P S

Reputation: 141

You can define it as an object key

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

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

Upvotes: 0

Karlan
Karlan

Reputation: 353

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);

Upvotes: 1

Related Questions