我是Node.js的新手。 目前,我正在帮助我的团队使用Nodejs开发一个安静的api。 我想问一下我是否必须在单个文件中实现所有app.get方法和业务逻辑?
例如,我的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')
});
如果我想构建一个文件调用family.js并从server.js中移出所有与家族相关的逻辑?
如何从server.js调用它?
有人可以帮忙吗?感谢。
答案 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'});
}