Thursday, 4 May 2017

ExpressJS - Routing Function

I created a separate JS file for specific server functions. Sample code as follow:

my-data.js

var exports = module.exports = {};
exports.getData = function (request, response) {
    var myData = [
        {
            "value": 1
        },
        {
            "value": 2
        },
    ];
    response.json(myData);
};

In my app.js, I'm trying to call that specific function when the request has been made.

Working sample of app.js

var express = require("express");
var app = express();
var port = process.env.PORT || 3000;
var myData = require("./lib/my-data.js");

app.engine(".html", require("ejs").__express);
app.set("views", __dirname + "/views");
app.set("view engine", "html");
app.use(express.static(__dirname));

// Line below is what I'm trying to achieve.
//app.get("/get-data", myData.getData(request, response));

// Working line
app.get("/get-data", function(request, response) {
    myData.getData(request, response);
});

app.get("*", function (request, response) {
    response.render("index");
});

app.listen(port, function () {
    console.log("Listening on port " + port);
});

It bothers me that the line app.get("/get-data", myData.getData(request, response)); doesn't work while

app.get("/get-data", function(request, response) {
        myData.getData(request, response);
});

does.

What is the difference between the two approach?

I prefer using the first one since it's clean and precise but I can't seem to make it work.



via Michael Ardan

No comments:

Post a Comment