我已經寫了一個簡單的api來使用GET/tours /:id檢索記錄。這是我在網址上編寫身份證時的作品。例如:/ tours/0,但是如果我在瀏覽器上只寫「/ tours」,或者瀏覽/「簡單節點api restfull,通過數組中的id獲取方法
我不得不編寫另一個塊來獲取帶有GET:/ toursall的完整數組,它是不正確的使用唯一的函數來獲取所有的記錄和id在同一個函數?我已經更新了我在書上找到的代碼我使用節點6.7.0和表達〜4.0.0
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
// custom 404 page
var tours = [
{ id: 0, name: 'Hood River', price: 99.99 },
{ id: 1, name: 'Oregon Coast', price: 149.95 },
];
app.get('/toursall', function(req, res) {
res.json(tours);
});
app.get('/tours/:id', function(req, res) {
responsetours = req.params.id !== undefined ?
tours.filter( function(obj) {return obj.id== req.params.id})
: tours;
res.json(responsetours);
});
app.use(function(req, res){
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});
// custom 500 page
app.use(function(err, req, res, next){
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});
app.listen(app.get('port'), function(){
console.log('Express started on http://localhost:' +
app.get('port') + '; press Ctrl-C to terminate.');
});
對所有記錄和一條記錄都有一個函數是一個好習慣? – stackdave
根據要求。如果它與你的一樣簡單,你可以有一個通用函數。但是如果你需要更多的操縱/外部呼叫,你可以用兩個不同的呼叫分開它們。事實上,如果你像MongoDB一樣從數據庫中檢索它,如果你有'findOne'和另一個'find'的單獨調用將會很好。 – Aruna