Prasanta Banerjee
Prasanta Banerjee

Reputation: 71

How to do POST Calls using Node & ExpressJS libraries

I'm working on Express with NodeJS to build some custom APIs. I've successfully build some APIs. Using GET, i'm able to retrieve the data.

Here's my index.js file with all the code.

const express = require('express');
const app = express();

//Create user data.
const userData = [
    {
        id : 673630,
        firstName : 'Prasanta',
        lastName : 'Banerjee',
        age : 24,
        hobby : [
            {
                coding : ['java', 'python', 'javascript'],
                movies : ['action', 'comedy' , 'suspense'],
                sports : "basketball"
            }
        ],
        oper_sys : ['Mac', 'Windows']
    },
    {
        id : 673631,
        firstName : 'Neha',
        lastName : 'Bharti',
        age : 23
    },
    {
        id : 673651,
        firstName : 'Priyanka',
        lastName : 'Moharana',
        age : 24
    },
    {
        id : 673649,
        firstName : 'Shreyanshu',
        lastName : 'Jena',
        age : 25
    },
    {
        id : 673632,
        firstName : 'Priyanka',
        lastName : 'Sonalia',
        age : 23
    },
    {
        id : 673653,
        firstName : 'Bhupinder',
        lastName : 'Singh',
        age : 25
    },
];

//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function(req, res) {
    res.json(userData);
});

//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
    const id = req.params.id;
    const user = userData.find(user => user.id == id)

    if(user){
        res.statusCode = 200
        res.json(user)
    }
    else {
        res.statusCode = 404
        return res.json({Error: ['ID Not Found']});
    }
});

//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
    console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});

Let's say i want to add id:12345 firstName:Michael lastName:Andrews to my userData. How am i supposed to it using POST calls?

I'm looking for code using which i can add new data to my userData, so that every time i do GET on it, i get the updated dataset.

Upvotes: 1

Views: 228

Answers (6)

knobiDev
knobiDev

Reputation: 480

Sending POST data

You need to specify Accept and Content-Type headers and stringify the JSON object in the POST request.

var userData = {
    id : 42069,
    firstName : 'Bob',
    lastName : 'Ross',
    age : 69
}


fetch('/api/employees', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(userData)
  })
  .then(res => res.json())
  .then(data => {
    console.log(data);
  })

How to receive POST on express

app.post('/api/employees', function (req, res) {
  console.log(req.body);
  //req.body will have your new user data. append that to exsisting userData array

  var newUser = {
    id: req.body.id,
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    age: req.body.age
  }

  userData.push(newUser);
  res.json({status: 'New user added'})
})

you need to declare the userData array globally or better use a database.

Upvotes: 0

Santhosh John
Santhosh John

Reputation: 728

I am considering you will push this data from any UI Front-End or via Postman and you know how to use it. The below solution will store data in an array, but for production, you must use a database as a solution to persist data.

Since you have not mentioned which Express version you are using, I recommend to firstly do install a package called body-parser.

For More Info: https://www.npmjs.com/package/body-parser

const bodyParser = require("body-parser"); // require it
    app.use(bodyParser()); // you may also use Express' built-in app.use(express.json()); as an alterative

    app.post('/api/employees', (req, res) => { //ES6 Feature: Arrow Syntax
       const { id, firstName, lastName } = req.body; //ES6 Feature: Object Destructuring
       const newUserData = {
           id, // when playing with arrays, try userData.length + 1 to auto-generate an id. Omit this field then; while passing from UI/Postman
           firstName, // pass a string from the UI/Postman. "Michael" in your case
           lastName // pass a string from the UI/Postman. "Andrews" in your case
        }; // ES6 Feature: Equivalent to {id: id, firstName: firstName, lastName: lastName}
        userData.push(newUserData); // use unshift(); instead of push() if you want to add it at the start of an array
        res.status(201).send(newUserData); // 201 = response code for creation. Instead of send(), json() can also be used.
    });

Please Note: I have included comments in every line of my code to make you understand it fully and will be helpful for others as well.

Upvotes: 0

Hassan Abbas
Hassan Abbas

Reputation: 1316

It would be something like this assuming your passing json in the post request: Your request body would be like this:

{
  "id": "1",
  "firstName": "First Name",
  "lastName": "Last Name"
}
app.post('/api/employees', function(req, res) {
    if(req.body) {
      userData.push(req.body)
    }
    else {
      res.statusCode = 500
      return res.json({Error: ['Object Missing']});
    }
});

Upvotes: 0

Prasanta Banerjee
Prasanta Banerjee

Reputation: 71

This is my full code snippet (index.js) As you can see, i have created a post call function which takes data from 'data' const and sends to the server. But still it doesn't work.

const express = require('express');
const app = express();
const bodyParser = require('body-parser');

//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false })); //support encoded bodies.
app.use(bodyParser.json());                          //support json encoded bodies.

//Create user data.
const userData = [
    {
        id : 673630,
        firstName : 'Prasanta',
        lastName : 'Banerjee',
        age : 24,
        hobby : [
            {
                coding : ['java', 'python', 'javascript'],
                movies : ['action', 'comedy' , 'suspense'],
                sports : "basketball"
            }
        ],
        oper_sys : ['Mac', 'Windows']
    },
    {
        id : 673631,
        firstName : 'Neha',
        lastName : 'Bharti',
        age : 23
    },
    {
        id : 673651,
        firstName : 'Priyanka',
        lastName : 'Moharana',
        age : 24
    },
    {
        id : 673649,
        firstName : 'Shreyanshu',
        lastName : 'Jena',
        age : 25
    },
    {
        id : 673632,
        firstName : 'Priyanka',
        lastName : 'Sonalia',
        age : 23
    },
    {
        id : 673653,
        firstName : 'Bhupinder',
        lastName : 'Singh',
        age : 25
    },
];

//Create the API endpoints with callback functions.
//Display a message.
app.get('/api/info', function(req, res) {
    res.send('Welcome to Employees API !!! Get access to free APIs.');
});

//Display all Employees data.
app.get('/api/employees', function(req, res) {
    res.json(userData);
});

//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
    //Retrieve the 'id' param from endpoint.
    const id = req.params.id;
    //Search for that 'id' param in the 'userdata'.
    const user = userData.find(user => user.id == id)

    //If found, then display the data to the user.
    if(user){
        res.statusCode = 200
        res.json(user)
    }
    //Else, display error message.
    else {
        res.statusCode = 404
        return res.json({Error: ['ID Not Found']});
        //res.send("Oops !!! No User with ID:" + id + " was found.")
    }
});

const data = [ {
    id : 12345,
    firstName : 'new',
    lastName : 'data',
    age : 29
}]

// POST employee data
app.post('/api/employees/', function (req, res) {
    const newUser = {
        id: req.body.id,
        firstName: req.body.firstName,
        lastName: req.body.lastName
    }

    userData.push(newUser);
});

//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
    console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});

Upvotes: 0

Shafkhan
Shafkhan

Reputation: 524

In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called body-parser. Please read this to get an idea about how to configure this on your app.

Then you have to add the POST route and the methods to your app.js file. Then hit the route with by parsing data through the body. I have edited your code and posted it below. I have commented on the places where I added the methods and middleware.

const express = require('express');
const app = express();

// require body parser middleware
const bodyParser = require('body-parser')

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

//Create user data.
const userData = [
    {
        id: 673630,
        firstName: 'Prasanta',
        lastName: 'Banerjee',
        age: 24,
        hobby: [
            {
                coding: ['java', 'python', 'javascript'],
                movies: ['action', 'comedy', 'suspense'],
                sports: "basketball"
            }
        ],
        oper_sys: ['Mac', 'Windows']
    },
    {
        id: 673631,
        firstName: 'Neha',
        lastName: 'Bharti',
        age: 23
    },
    {
        id: 673651,
        firstName: 'Priyanka',
        lastName: 'Moharana',
        age: 24
    },
    {
        id: 673649,
        firstName: 'Shreyanshu',
        lastName: 'Jena',
        age: 25
    },
    {
        id: 673632,
        firstName: 'Priyanka',
        lastName: 'Sonalia',
        age: 23
    },
    {
        id: 673653,
        firstName: 'Bhupinder',
        lastName: 'Singh',
        age: 25
    },
];

//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function (req, res) {
    res.json(userData);
});

//Display employee data based on 'id' param.
app.get('/api/employees/:id', function (req, res) {
    const id = req.params.id;
    const user = userData.find(user => user.id == id)

    if (user) {
        res.statusCode = 200
        res.json(user)
    }
    else {
        res.statusCode = 404
        return res.json({ Error: ['ID Not Found'] });
    }
});

// POST emplyee data
app.post('/api/employees/', function (req, res) {

    // catch request body data, break it down and assign it to a variable
    // you can just parse req.body as well
    const newUser = {
        id: req.body.id,
        firstName: req.body.firstName,
        lastName: req.body.lastName
    }

    userData.push(newUser);
    res.status(200).json(newUser);
});

//start the node server.
const PORT = 7777;
app.listen(PORT, function () {
    console.log('Your server is up & running at localhost:' + PORT + '. Please hit the APIs.');
});

Upvotes: 1

sharad shetty
sharad shetty

Reputation: 382

const express = require('express');
const app = express();

//including the body-parser
app.use(express.json()).use(express.urlencoded({ extended: false }));

//Create user data.    

//your get routes     

//post route
app.post('/api/employees',function(req,res) {
  //posted data is available in req.body
  //do any validations if required
  userData.push(req.body);
  res.send("success")
}

//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
    console.log('Your server is up & running at localhost:'+PORT+'. Please hit 
the APIs.');
});

you can check the post method for express here

Upvotes: 0

Related Questions