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
Post a Comment