Come esportare una variabile che si trova in una classe in Nodejs

Aug 24 2020

Questo è il mio file loginHandler.js

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

module.exports = new LoginHandler();

Voglio accedere alla variabile merchantIdsu un altro file

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

Ma merchantId non è definito. Puoi dirmi cosa sto sbagliando?

Qui puoi vedere il codice su Glitch = https://glitch.com/edit/#!/turquoise-spiky-chrysanthemum

Risposte

1 Karlan Aug 24 2020 at 10:46

Il mio loginhanderler.js

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

module.exports = new LoginHandler();

Il mio index.js

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

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

loginHandler.returnURLForIframe(req);

console.log(loginHandler.merchantId);
1 NehalJaisalmeria Aug 25 2020 at 11:50

L'ho risolto aggiungendolo a una variabile d'ambiente su loginHandler.js

process.env.MERCHANT_ID = req.params.merchantId

e poi su responseHandler.js, ho avuto accesso a quella variabile

merchantId : process.env.MERCHANT_ID

SarathPS Aug 24 2020 at 11:18

Puoi definirlo come chiave oggetto

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

    returnURLForIframe(req, res) {
      this.merchantId = req.params.merchantId;
    }  
}
malarres Aug 24 2020 at 11:32

nuovo LoginHandler

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

module.exports = new LoginHandler();

PER RIFERIMENTO FUTURO (anche per me stesso)

È stato difficile rilevare quale fosse l'errore, quindi per me è stato utile cambiare il nome della variabile:

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

module.exports = new LoginHandler();

Poi ho visto che l'errore era ReferenceError: other is not definede potevo risolverlo.

Inoltre, oltre alla registrazione, era necessario chiamare returnURLForIframeper vedere l'errore

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