2016-11-06 26 views
0

我已經寫了一個簡單的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.'); 
}); 

回答

1

您可以在年底與?嘗試可選PARAM如下,

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); 
}); 
+0

對所有記錄和一條記錄都有一個函數是一個好習慣? – stackdave

+0

根據要求。如果它與你的一樣簡單,你可以有一個通用函數。但是如果你需要更多的操縱/外部呼叫,你可以用兩個不同的呼叫分開它們。事實上,如果你像MongoDB一樣從數據庫中檢索它,如果你有'findOne'和另一個'find'的單獨調用將會很好。 – Aruna

0
  1. app.get('/toursall', function(req, res) { =>app.get('/tour', function(req, res) {。您的REST API將更加consistens。
  2. 硬編碼的數組不是最好的解決辦法,如果你有成千上萬的元素。也許,您需要將數據存儲在數據庫中,例如在MongoDB中。
  3. 如果您不需要數據庫,然後用JSON文件之旅,讓var tours = require('./tours.json');
+0

感謝GALK,我不得不選擇另一個響應,因爲我的第一個問題是瞭解參數,我只是練習節點的基礎和表達,之前使用db和真實結構。 – stackdave

相關問題