0
我有一個簡單的工作NodeJS測試應用程序與快車,mongodb和貓鼬。至於現在,我正試圖清理我的代碼並找出最佳實踐。我的一個步驟是提取REST路由,但是我遇到了一個問題,那就是我對可以做到的方式感到困惑,2016年最好的方法是什麼?導出nodejs REST路徑(帶快遞)
我的代碼(app.js):
"use strict"
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Subjects = require('./models/Subjects').model('Subjects');
const Students = require('./models/Students').model('Students');
const app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
mongoose.connect('mongodb://localhost/schoolapp');
app.get('/subjects', function(req, res) {
Subjects.find({})
.exec(function(err, subjects) {
if(err) {
res.send('error msg has occured');
} else {
res.json(subjects);
}
})
});
app.put('/subjects', function(req, res) {
const query = {name: req.body.name};
const update = {$inc: {votes: 1}};
Subjects.findOneAndUpdate(query, update,
function(err, newSubject) {
if(err) {
console.log('An error occured');
} else {
res.send(newSubject);
}
})
})
app.post('/subjects', function(req, res) {
let newSubject = new Subjects();
newSubject.name = req.body.name;
newSubject.level = req.body.level;
newSubject.votes = 0;
newSubject.save(function(err, subject) {
if(err) {
res.send('error saving subject');
} else {
res.send(subject);
}
})
});
app.get('/students', function(req, res) {
Students.find({})
.exec(function(err, students) {
if(err) {
res.send('error saving students');
} else {
res.send(students);
}
})
})
app.post('/students', function(req, res) {
let newStudent = new Students();
newStudent.name = req.body.name;
newStudent.save(function(err, student) {
if(err) {
res.send('error saving student');
} else {
res.send(student);
}
})
})
app.put('/students', function(req, res) {
const query = {"_id": req.body.id};
const update = {$push: {subjects: req.body.name}};
Students.findOneAndUpdate(query, update,
function(err, newSubject) {
if(err) {
res.send('something went wrong');
} else {
res.send(newSubject);
}
});
})
app.listen(3000, function() {
console.log('app listening on port 3000');
});
我想提取/students
和/subjects
作爲獨立的文件,並要求他們在我的app.js.
我試圖約3種方法產生不同的結果,其中包括:
module.exports = function(app) {
app.get('/students', ...)
}
和app.js:
var students = require(./rest/students)(app);
非常感謝:)
http://expressjs.com/en/api.html#router –
是,@ MH-cbon是正確的:這是使用多個路由器的最佳例子。 – robertklep
我不打算提供html模板,我只是想使用節點作爲休息API,這仍然是多路由器的完美情況嗎? – Baki