Nodejs is a single threaded server-side platform which has gained it’s unique niche due it’s asynchronous feature thereby enhancing the speed of execution and efficiency.
The unique feature of nodejs is that you can create request and server for many web applications.
Getting Started:
1. Let’s start of with creating a basic GET request using nodejs. We will request for a username through GET request which is provided by the user.
a) Developing a GET request on server to receive and print the username
server.js
var express = require('express'); var app = express(); app.get('/', function (req, res) { res.sendFile( __dirname + "/" + "index.html" ); }) app.get('/getUsers', function (req, res) { // Prepare output in JSON format response = { first_name : req.query.first_name, last_name : req.query.last_name }; console.log(response); res.end(JSON.stringify(response)); }) app.listen('8081'); console.log("server is up and running..");
Express module helps you create a request and listen function binds the ip to the server.
b) To send a request, we first create an interface where we can input the username.
index.html
<html> <body> <form action = "http://localhost:8081/getUsers" method = "GET"> First Name: <input type = "text" name = "first_name"> <br> Last Name: <input type = "text" name = "last_name"> <input type = "submit" value = "Submit"> </form> </body>
2. Running the server
Now that we are ready with server and interface, let’s run them.
To run the node server, type the following command(presuming you have nodejs installed or you may install it from here)
node server.js
Output
server is up and running..
3. To send a request using the interface, open http:localhost:8081 in your browser and you will be redirected to webpage where you can input username
4. Click on “Submit”, which sends a request to the server and you’ll get response that returns the username.
Here we are just printing the user name sent by the user. Similarly, we may save it to the file or database.
Hope this helped you!
Happy learning!