javascript - How to properly route to JSON entry in Express -


i building simple express-based api serve json data file. it's working fine i'd add functionality. json file of following format: (portions omitted)

[{   "id": "1",   "name": "george washington",   "page": "http://en.wikipedia.org/wiki/george_washington",   "date1": "30/04/1789",   "date2": "4/03/1797",   "party": "independent ",   "img": "georgewashington.jpg",   "thumb": "thmb_georgewashington.jpg",   "homestate": "virginia" } 

and here's snippet index.js express routing:

var express = require('express'); var app = express();  app.set('port', process.env.port || 3000);  var mydata = require('./data.json');  app.get('/api', function(req, res){ res.json(mydata); });  app.get('/api/:id', function(req, res){   res.json(mydata[req.params.id]);   }); 

a call /api gives whole dataset, while call /api/1 gives first entry, hoped. add third (or more route) allows user drill down specific items in json. example call to

https//<blah>/api/1/homestate 

would yield

"homestate": "virginia" 

can using parameters, or need iterate on json based on entered id? pointers code examples appreciated.

it can accomplished route parameters.

app.get('/api/:id/:property', function(req, res){   var response = {};   response[req.params.property] = mydata[req.params.id][req.params.property]   res.json(response); }); 

you going want add error handling make things more robust, otherwise app crash if route parameters aren't valid.


Comments

Popular posts from this blog

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -