Austin Truex Austin Truex - 4 days ago 6
Node.js Question

Pass data from express route into node module export function

I am new to node, I think I need to use middleware, but I can't warp my head around what it is actually used for, or if this is where it is meant to be used. I have data that is being posted from my view into an express route.

ROUTE - route.js

var GetPlayer = require('./models/getPlayer.js');
module.exports = function(app) {
app.post('/api/getPlayer', function(req, res) {
//GetPlayer.apiGetPlayer(req.body.username);
console.log(req.body.username); //this logs the correct data
});
}


but now I need to pass that data into a node api call and send that response back to the client. But I can not get the route to call that function or pass the data into it.

MODULE.EXPORT - getPlayer.js

module.exports = {
apiGetPlayer: function(error, res) {
console.log("in get player");
console.log(res);
}
}

Answer

You would only want to use an Express middleware if this is something you want to do for more than one route (ie. parsing request body's from JSON to actual Object using body-parser). That seems like it could be overkill based on the supplied code. One way to approach this is to just take the username and pass a callback function in to getPlayer. Then when the callback function passed to apiGetPlayer() returns, respond back to the requester based on the result of apiGetPlayer().

getPlayer.js

module.exports = 
    // callback is an error-first callback function
    apiGetPlayer: function(username, callback) {
        let err;
        let player;

        // Logic for getting player go here

        // If an error occurs return an error to the callback
        if (err)
            return callback(err, null);

        return callback(null, player);
    }
}

/api/getPlayer route

app.post('/api/getPlayer', (req, res) => {
    GetPlayer.apiGetPlayer(req.body.username, (err, player) => {
        if (err)
            return res.status(500).send(err);

        return res.status(200).send(player);
    });
});
Comments