Adding a simple GET
request support is fairly simple, and you've seen this before already in the app we built. Here is some sample code that responds to a GET
request and returns a simple JavaScript object as JSON. Insert the following code in the routes section where we have the // TO DO: Setup endpoints ... waiting
comment:
router.get('/test', function(req, res) { var data = { name: 'Jason Krol', website: 'http://kroltech.com' }; res.json(data); });
Just like we set up viewModel
in Chapter 5, Dynamic HTML with Handlebars, we create a basic JavaScript object that we can then send directly as a JSON response using res.json
instead of res.render
. Let's tweak the function a little bit and change it so that it responds to a GET
request against the root URL (that is /
) route and returns the JSON data from our movies file. Add this new route after the /test
route added previously:
router.get('/', function(req, res) { res.json(json); });
The res
(response) object in Express has a few different methods to send data back to the browser. Each of these ultimately falls back on the base send
method, which includes header information, statusCodes, and so on. res.json
and res.jsonp
will automatically format JavaScript objects into JSON and then send using res.send
. res.render
will render a template view as a string and then send it using res.send
as well.
With that code in place, if we launch the server.js
file, the server will be listening for a GET
request to the /
URL route and will respond with the JSON data of our movies collection. Let's first test it out using the Postman REST Client tool:
GET
requests are nice because we could have just as easily pulled that same URL via our browser and received the same result:
However, we're going to use Postman for the remainder of our endpoint testing as it's a little more difficult to send POST
and PUT
requests using a browser.
3.147.58.196