Basic HTTP calls using Node.js without Expressjs
Node.js is designed for developing scalable network applications. We may face a situation where we need to perform HTTP calls from Node server to external server.
Request is one of the popular node package which is designed to simplify HTTP calls and it does.
- GET.
- POST.
- PUT.
- DELETE.
GET Request:
GET is a http call to retrieve or fetch data from server by providing specific parameter in URL’s. GET is fast and used widely in web server to server static pages.
example
var request=require("request");
request.get("http://codeforgeek.com",function(error,response,body){
if(error){
console.log(error);
}else{
console.log(response);
}
});
POST request :
POST is http call to send some data to server. POST request is very useful for performing some secure operations such as creating new resource at server, performing login etc.
example
var request=require("request");
var options = {
method: 'POST',
uri: '-----URL---------',
form: {
var_1:var_1,var_2:var_2,var_3:var_3
},
headers: {
'----HEADER DATA------'
}
};
request(options, function(error, response, body) {
if(error){
console.log(error);
}else{
console.log(response);
}
});
});
PUT request:
PUT is HTTP call to store the particular data to the web server. It takes endpoint URL as input and replies with response, body.
example
var request=require("request");
request.put('http://mysite.com/img.png',function(error,response,body){
if(error){
console.log(error);
}else{
console.log(response);
console.log(response);
}
});
DELETE request :
As name implies DELETE is http command which is used to delete some resource from the server. You have to provide endpoint url to execute this operation.
example
var request=require("request");
request.del("-------url------",function(error,response,body){
if(error){
console.log(error);
}else{
console.log(response);
console.log(response);
}
});
Below example create a http post request without using ExpressJS framework
Example : server.js
const http = require('http');
const { parse } = require('querystring');
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
collectRequestData(req, result => {
console.log(result);
res.end(`Parsed data belonging to ${result.fname}`);
});
}
else {
res.end(`
<!doctype html>
<html>
<body>
<form action="/" method="post">
<input type="text" name="fname" /><br />
<input type="number" name="age" /><br />
<input type="file" name="photo" /><br />
<button>Save</button>
</form>
</body>
</html>
`);
}
});
server.listen(3000);
function collectRequestData(request, callback) {
const FORM_URLENCODED = 'application/x-www-form-urlencoded';
if(request.headers['content-type'] === FORM_URLENCODED) {
let body = '';
request.on('data', chunk => {
body += chunk.toString();
});
request.on('end', () => {
callback(parse(body));
});
}
else {
callback(null);
}
}
To run this program execute this command in node “node server.js”