问题
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
回答1:
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);
回答2:
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
回答3:
You can define it as an object key
class LoginHandler {
constructor() {
this.merchantId = '';
}
returnURLForIframe(req, res) {
this.merchantId = req.params.merchantId;
}
}
回答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");
来源:https://stackoverflow.com/questions/63558836/how-to-export-a-variable-which-is-in-a-class-in-nodejs