Austin Truex Austin Truex - 1 year ago 101
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) {'/api/getPlayer', function(req, res) {
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");

Answer Source

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().


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'/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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download