Sharanabasu Angadi
Sharanabasu Angadi

Reputation: 4372

Node.js calling function from other function not working

Profile.js code goes as below

'use strict';
var service = require('../services/Profile');
class Profile {
    updateProfile(req, resp) {
        this.updateUserDetails(req, resp);
    }
     updateUserDetails(req, resp){
        var admin = req.body;
        resp.json({"success":true,"message":"User Updated"});
    }
}
module.exports = new Profile();

server.js code goes as below

...... Some code -------

var profile = require("./controllers/Profile")
app.put("/api/profile", auth, profile.updateProfile);


...... Some code -------

When I make the call <>/api/profile I am getting error

TypeError: Cannot read property 'updateUserDetails' of undefined ,
 (at line number of code this.updateUserDetails(req, resp);)

Since there is some common logic so I need to move to some function and want to call in different place, but I am getting this error. I am new to node js looking for help.

Upvotes: 0

Views: 313

Answers (3)

Vinod Kumar Kayartaya
Vinod Kumar Kayartaya

Reputation: 36

change your code to:

var prof = new Profile();
module.exports = prof;

and then use it in the other method like this:

class Profile {
    updateProfile(req, resp) {
        prof.updateUserDetails(req, resp);
    }

this should work just fine.

Upvotes: 0

Sharanabasu Angadi
Sharanabasu Angadi

Reputation: 4372

I moved the function out of class and using it, it worked

'use strict';
var service = require('../services/Profile');
class Profile {
    updateProfile(req, resp) {
        updateUserDetails(req, resp);
    } 
}
function updateUserDetails(req, resp){
        var admin = req.body;
        resp.json({"success":true,"message":"User Updated"});
    }

module.exports = new Profile();

Upvotes: 0

slebetman
slebetman

Reputation: 113866

This is a classic misunderstanding of how this works in javascript. I'd suggest you search stackoverflow for the phrase "how this works in javascript".

As for your code, you either need to do this:

app.put("/api/profile", auth, function (req,res) {
    profile.updateProfile(req,res)
});

or this:

app.put("/api/profile", auth, profile.updateProfile.bind(profile));

Upvotes: 1

Related Questions