Let's begin by implementing basic GET methods for our resources. You may recall that we mentioned before that a good REST API should at least implement two of them—GET by ID and GET all. Since we like to be standards-compliant, that is what we will use here.
Our first order of business is to provide a way for our Node.js instance to differentiate between the different URLs that it receives requests for. Until now, our server only had to handle requests to its root URL (http://localhost:8080/
), but in order to do something more interesting, we want to be able to generate custom responses for more specific URLs, such as http://localhost:8080/api/products
.
Fortunately, Node.js again provides an out-of-the-box way to achieve this—the URL module.
Add the following just after the var http = require('http');
line:
var URL = require('URL');
This will import the URL module. We can now use it to break down the incoming requests and take action depending...