In this article, we will see how to expose REST services using Node.JS and Express.JS. Express is a lightweight web framework built for Node.JS.
Now we will see how to build REST services using Express.JS. Follow the steps to set up the Express and to expose the REST APIs.
Step 1: Open the command prompt and create a folder. In this example, I have created a folder called “express_example”.
Step 2: Move to “express_example” folder and run the below command. During this command execution user need to provide some inputs. After the execution, you will see “pacakge.json” file under “express_example” folder.
npm init
Step 3: Now, install node “express” module by running the below command.
npm install express --save
Step 4: Now, create a JS file to expose the REST services. In this example, I have created “express_exmaple.js” file. As a first step, we need to import the “express” node module by keeping the below code.
var express = require('express');
The below code will create an HTTP server behind the scenes.
var app = express();
If we are not setting the port to listen, by default express will bind the HTTP server to run on 3000 port. In this example, I want to listen to the requests on port 8080. The listen function call will take the port to listen.
app.listen(8080, function() { console.log("The Node Server is running on port 8080"); });
Now we will expose simple REST service. This service will get the product details for the product id passing as part of the query string. The example request URL is “http:// localhost:8080/getProduct?id=92879809”
app.get('/getProduct', function(req, res) { var product_id = req.query.id; console.log("The product id [" + product_id + "]"); var product = new Object(); product.name = "Samsung Galaxy J5"; product.price = 178; res.send(product); });
If you want to pass the id as part of request URI, let say “http:// localhost:8080/getProduct/92879809”, then we need to access id as request param. The below example uses the same.
app.get('/getProduct/:id', function(req, res) { var product_id = req.param.id; console.log("The product id [" + product_id + "]"); var product = new Object(); product.name = "Samsung Galaxy J5"; product.price = 178; res.send(product); });
In the next article, we will see how to create Node Express Application using “express-generator".
I keep getting ‘The product id is [undefined]’ from the server terminal. Any idea what might be causing that?
I have mentioned two ways of passing request parameters and the sample URLs for the same in the article.
If you are passing the request parameter as shown below,
http:// localhost:8080/getProduct?id=92879809 then try to access the same as “req.query.id”
If you are passing the request parameter as shown below,
http:// localhost:8080/getProduct/92879809 then try to access the same as “req.param.id“