stackdave stackdave - 1 month ago 7
Node.js Question

simple node api restfull , get method by id from array

I've written a simple api to retrieve records with GET /tours/:id. It's works when I write the id on the url. Ex: /tours/0 , but not if I write on the browser just "/tours" , or tours/"

I've had to write an another block to get the complete array with GET: /toursall , or it's not right use an onlye function to get all the records and by id in the same function?, I've update the code that i've found on a book. I'm using node 6.7.0 and express ~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.' );
});

Answer

You can try with ? at the end for an optional param as below,

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