1

I am new to Node.js. Currently I am helping my team to develop a restful api with Nodejs. I would like to ask if I have to implement all the app.get methods and business logics in single file?

For example, my server.js:

var express = require('express')
var bodyParser = require('body-parser')
var app = express()
let family = {}

app.use(bodyParser.json())

app.route('/family')
  .get(function (request, response) {
    response.json(family)
  })
  .post(function (request, response) {
    family[request.body.isbn] = {
      name: request.body.name,
      relationship: request.body.relationship,
      age: request.body.age
    }

    response.json({message: 'Success'})
  })

app.listen(8080, function () {
  console.log('Server is started')
});

How if I wanna build a file call family.js and move all family related logic inside from server.js?

And how to call it from server.js?

Anybody can help? thanks.

TechHolic
  • 13
  • 3
  • No you don't have to. You can define all family logic as functions in other file and export those functions. Read : http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it – Rohan Kumar Apr 15 '17 at 14:40

1 Answers1

5

Off course you can. The main thing is, how do you pass app reference to your modules. I've created modules and passed app instance in the main function of the module.

Folder Structure:

server.js
    /routes
        family.js
        login.js
        user.js
        ...

server.js

//include
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json())

//init routes
require('../routes/family')(app); //passing "app" instance
require('../routes/login')(app);
require('../routes/user')(app);

//start server
app.listen(8080, function () {
  console.log('Server is started')
});

family.js

//routes
module.exports = function(app) {  //receiving "app" instance
    app.route('/family')
        .get(getAPI)
        .post(postAPI);
}

//API functions
function getAPI(request, response) {
    response.json(family);
}

function postAPI(request, response) {
    family[request.body.isbn] = {
        name: request.body.name,
        relationship: request.body.relationship,
        age: request.body.age
    }

    response.json({message: 'Success'});
}
Shaharyar
  • 12,254
  • 4
  • 46
  • 66
  • Thanks a lot. It works for me after removing "route('/family')" in family.js. (It alerts app.route is not a function, why?) – TechHolic Apr 15 '17 at 15:20
  • and why did you remove `app.route('/family')` from `family.js`? It creates the route.. – Shaharyar Apr 15 '17 at 15:22
  • Error alerts "app.route is not a function". I modified the code to "app.get(getAPI); app.post(postAPI);" and it can run... – TechHolic Apr 15 '17 at 15:41
  • @TechHolic Express works with both syntax, I am not sure why the other one is throwing error as I haven't used it for a while.. – Shaharyar Apr 16 '17 at 14:46