How to make a Node post request
Overview
In this shot, we will learn how to make a post request to an API using the Node in-built module request. We will also use and learn the request.post() method.
Syntax
The following is the syntax for the post request:
request.post(URL, DATA, CallBack());
Parameter
URL: The first parameter is the URL of the API to which we are making a post request.DATA: Second is the JSON object; this data is sent to the API to make a POST request.Callback(): This is a function that will run after the completion or failure of the POST method.
Code
The following is the code for the post request:
var request = require('request');request.post(//First parameter API to make post request'https://reqres.in/api/users',//Second parameter DATA which has to be sent to API{ json: {name: "paul rudd",movies: ["I Love You Man", "Role Models"]}},//Thrid parameter Callack functionfunction (error, response, body) {if (!error && response.statusCode == 201) {console.log(body);}});
Code explanation
-
In line 1, we import the
requestmodule and create an instance. -
In line 3, we use the
request.post()method. -
In line 5, we have the
URL(API), which is the first parameter of therequest.post()method. This is the server or site we are requesting. -
In line 8, we have
Data, which is the second parameter for the methodrequest.post(). This data is sent to the API. Here, we are sending _JSON data with two properties,nameandmovies. -
In line 15, we have the
Callback()function, which will execute after thepostmethod is completed. If the post request is successful, then thepostwill return with aresponseandbody. If it fails to make a post request, then it will return anerror. -
In line 16, we used the
ifcondition to check if ourpostrequest is successful or not. -
In line 17, after checking the
ifcondition, this line will execute, which means we have no error while makingpostrequest and we have successfully made apostrequest. We usedconsole.log(body)to print the response from the API. The body parameter contains the response JSON from the API.
Output
Click the “Run” button and check the result. We have successfully completed the task to make a POST request for the output. We get a JSON object, which is returned by the API after creating. After JSON, you can see the response.statusCode is 201 which implies created.