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

simple node api restfull , get method by id from array

我写了一个简单的 api 来使用 GET /tours/:id 检索记录。当我在 url 上写 id 时,它起作用了。例如: /tours/0 ,但如果我只在浏览器上写 "/tours" 或 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.' );
});
  1. app.get('/toursall', function(req, res) { => app.get('/tour', function(req, res) {。你的 REST API 会更加一致。
  2. 如果您有数千个元素,硬编码数组不是最佳解决方案。也许,您需要将数据存储在数据库中,例如 MongoDB.
  3. 如果你不需要数据库,那么使用json文件进行游览并制作var tours = require('./tours.json');

您可以尝试在末尾使用 ? 作为可选参数,如下所示,

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