简单节点api restfull,从数组中获取id方法

时间:2016-11-06 09:07:40

标签: node.js express restful-architecture

我写了一个简单的api来检索带有GET / tours /:id的记录。当我在URL上写id时,它是有效的。例如:/ tours / 0,但如果我只是在浏览器上写“/ tours”或者游览/“

,那就不行了

我必须编写另一个块来获取带有GET的完整数组:/ toursall,或者使用onlye函数来获取所有记录并通过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.' );
});

2 个答案:

答案 0 :(得分:1)

您最后可以尝试使用?作为可选参数,如下所示

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

答案 1 :(得分:0)

  1. app.get('/toursall', function(req, res) { => app.get('/tour', function(req, res) {。你的REST API会更加有用。
  2. 如果您有数千个元素,硬编码数组不是最佳解决方案。也许,您需要将数据存储在数据库中,例如在MongoDB中。
  3. 如果您不需要数据库,请使用json文件进行巡视并制作var tours = require('./tours.json');