1

aUtil.js

module.exports = {
    successTrue: function(data) { 
        return { data: data, success: true };
    },
    isLoggedin: async (req, res) { 
        //decoded token in req header
        //if decoded token success, 
        res.json(this.successTrue(req.decoded));
    }
}

that function call in test.js

router.get('/check', aUtil.isLoggedin, async (req, res) => { ... })

I want to use the function above in that function.

But I keep getting errors.

ReferenceError: successTrue is not defined

I tried many ways.

  1. insert 'const aUtil = require('./aUtil')`
  2. change to 'res.json(successTrue( ... )'
3
  • a little suggestion please use exports.successTrue = function () { } this is alot more cleaner Commented Jan 25, 2019 at 7:53
  • @AfrazAhmad That's subjective. For one I don't think it's cleaner at all. Commented Jan 25, 2019 at 7:55
  • isLoggedin doesn't need to be async either. Commented Jan 25, 2019 at 7:56

2 Answers 2

3

Use this:

module.exports = {
    successTrue: function() {
      return { foo: 'bar' } 
    },

    isLoggedin: function() {
      console.log(this.successTrue())
    }
}

You're exporting an object, so this refers to itself.

Also make sure you're binding aUtils if you're using it as middleware like so:

router.get('/check', aUtil.isLoggedin.bind(aUtil), async (req, res) => { ... })

Sign up to request clarification or add additional context in comments.

9 Comments

I tried the same way, but I got an error. 'TypeError: this.successTrue is not a function'
How are you calling aUtil.isLoggedin? Edit your post to add the relevant code.
The function name was typed incorrectly. successTrue is right. I modified it.
The same concept stands. You should do: res.json(this.successTrue(req.decoded))
That's the old code, and I've corrected it when I saw your answer, but there's an error.
|
2

Try this :

const aUtil = {
    successTrue: function() { //return json obj },
    isLoggedin: function() { 
        res.json(aUtil.successTrue( ... ));
    }
}
module.exports = aUtil;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.