NodeJs - [Restful API]如何在不同的js文件中分离app get方法?

时间:2017-04-15 14:33:29

标签: javascript node.js rest api

我是Node.js的新手。 目前,我正在帮助我的团队使用Nodejs开发一个安静的api。 我想问一下我是否必须在单个文件中实现所有app.get方法和业务逻辑?

例如,我的s​​erver.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')
});

如果我想构建一个文件调用family.js并从server.js中移出所有与家族相关的逻辑?

如何从server.js调用它?

有人可以帮忙吗?感谢。

1 个答案:

答案 0 :(得分:3)

当然可以。主要的是,如何将app引用传递给您的模块。我已经创建了模块并在模块的main函数中传递了app实例。

文件夹结构:

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