Category: GET request in nodejs

Develop a POST and GET request to add and get data from a file in nodejs

So far, we’ve learnt developing nodejs API with GET and POST request in json format. Today, let’s raise our learning bar and learn saving or writing the json data to a file.

Since, nodejs has huge repository of node modules, it makes our life pretty easy to do almost anything just by importing the respective module.

For instance, in this post, we are going to save the json data to a file for which we need a file stream library that enables us to read and write the data. With nodejs, it is just simple to accomplish this. All you need to do is, install the ‘fs’ module using npm(Node Package Manager) using following command in terminal:

npm install fs
Similarly, body parser is used to extract the entire body portion of an incoming request stream which is exposed on req.body. You may install it using following command:
npm install body-parser

Let’s first add the user data which includes the user name, profession and password. Since, we require the user’s input here, let’s use POST request to send these parameters.

Here, I am saving the data to a file named users.json

server.js

var express = require('express');

var app = express();

var fs = require("fs");

var bodyParser = require('body-parser');

app.use(bodyParser.json({limit: '5mb'}));//set the limit of maximum request body size

app.use( bodyParser.json() );       // to support JSON-encoded bodies

app.use(bodyParser.urlencoded({     // to support URL-encoded bodies

        extended: true,

        limit: '5mb'

}));

   

//saving the user to file

app.post('/addUser', function (req, res) {

    // First read the parameters sent through body.

    var name = req.body.name;

    var password = req.body.password;

    var profession = req.body.profession;

//creating a JSON object with the received parameters.

    var user = {

        "user1" : {

            "name" : name,

            "password" : password,

            "profession" : profession,

            "id": 1

        }

    }

user = JSON.stringify(user);

fs.writeFile('users.json', user);

        console.log("added");

res.json({'message' : 'User added', 'details' : JSON.parse(user) });

})     


//To list the saved users, here's a GET request


app.get('/listUser', function (req, res) {

    // First read existing users.

    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {

        data = JSON.parse( data );

        console.log( data );

        res.json(data);

    });

})

// set a port for the server to listen

var server = app.listen(8081, function () {

    var port = server.address().port

    console.log("Example app listening at http://localhost:%s", port)


})

Now let’s run the server to save the user data:

node server.js

Example app listening at http://localhost:8081

To insert the data, send a POST request, you may send the data through form-data or use third party REST client apps like REST client, Http Request or Post Master.

I have used a HTML form to add the user

Here’s the HTML code :

<html>

<title>Add user</title>

<body>

<form  action="http://localhost:8081/addUser" method="post">

  <input value = "name" type="name" name="name" />

  <input value = "profession" type="profession" name="profession" />

  <input value = "password" type="password" name="password" />

  <input type="submit" value="Add"  name="submit" />

  <input type="reset" value="Clear"/>

</form>

</body>

</html>

Output


Here the data is inserted to users.json file now. To fetch the data from file, we use GET request.

Enter the url “http://localhost:8081/listUser” in your browser and it lists the users in the file.

That’s it! Hope this was of help. Happy coding!

Developing a GET request to pass username using nodejs

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">&nbsp; <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!