Learn to Code via Tutorials on Repl.it

← Back to all posts
Using the request module in nodejs to send GET and POST requests.
h
PDanielY (280)

Today, we are going to learn how to use the request module in nodejs. The request module is like the https module but with better features and it is easier to use the request module. Click here to start a new nodejs repl for using the request module. You should be on a page like this when you repl is created

Once you are on that page require the module request and run the repl. Once the repl is done download request you can start to program.

Creating get requests

Creating get requests is probably the most easiest thing to do with the request module.
Here is an example of creating a get request

const request = require("request")
request({
uri: "https://repl.it"
},(err,resp,body)=>{
if(err){
console.log(err)
return
}
console.log(body)
})

Now let me explain what every piece of code does. The first line of code jutst requests the module which you should have done already. Then we use the request function from the request module to send a get request. We pass a JSON value in. The value is URI. URI stands for the URL that the module should send a get request with. Then we have a callback function. The callback function returns 3 values. Err,resp, and body. Err is the error if there was an error. Resp is basically the headers the website gave. Then we get the body. The body is the value returned from the request. You can either do body or resp.body. In this case, the body would be the code for repl.it.

Creating post requests

To create a post request you can do:

request = require("request")
request.post({
uri: "https://repl.it/login",
json: {username: "PDanielY",password: "notmypassword"}
},(err,resp,body)=>{
if(err){
console.log(err)
return
}
console.log(body)
})

Now let me explain what every line of code means.
The first line is how we request the module request which you should have already done by now. Then we create a post request with the post function from the request module, we give it two JSON values. We give the URL and then the JSON. The url is the url that we are posting and the json is the thing we are sending in JSON value. Then we have the callback. The callback returns the err,resp, and body. The err is the error if there is a error. The resp is basically the header and the body is the body. In this case it would return a JSON value with info about PDanielY if the info I submitted was correct.

Footer

That is the end of this tutorial. If you like it upvote and you can find more info here. Have any questions? comment on this post