简体   繁体   中英

NodeJs - [Restful API] How to separate app get methods in different js files?

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.

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'});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM