CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Programming How To Create HTTP Request In NodeJS

How To Create HTTP Request In NodeJS

Rana Ahsan September 14, 2014 3 Comments


 How To Create HTTP Request In NodeJS    

Most of new programmer starts learning nodejs, assuming have knowledge in javascript already, by creating a web-server in simple easy few lines of codes. Well, do you know that the same http module, which helps us creating a web server, can also be used to perform http request to another remote server? Today, in this tutorial, which is intended for nodejs beginners, I will try to explain how we can:

  • Perform various HTTP requests(GET/POST etc)
  • Perform HTTPs Requests(to request over ssl)
  • Proxying an incoming request

Lets explore the areas one by one.

Perform Simple NodeJS HTTP Request:

Generating a traditional http request is very easy. We just have to pass the basic options(host,uri,port,method) and the callback function and we are good to go. We will receive the response object as parameter on the callback, which will have the response headers/status code, but not the response body yet. to get the data, we will be to listen to the ‘data’ event on the response object. Here is the basic nodejs code example to do this:

var client       = require('http');
var options = {
            hostname: 'host.tld',
            path: '/{uri}',
            method: 'GET', //POST,PUT,DELETE etc
            port: 80,
            headers: {} //
          };
    //handle request;
pRequest    = client.request(options, function(response){
console.log("Code: "+response.statusCode+ "\n Headers: "+response.headers);
response.on('data', function (chunk) {
      console.log(chunk);
});
response.on('end',function(){
      console.log("\nResponse ended\n");
});
response.on('error', function(err){
      console.log("Error Occurred: "+err.message);
});

});

as you can see, response has two other events. We have to catch the ‘end’ event to know when we are finished getting the response. And ‘error’ event will trigger if something goes wrong with the request.

Also though there are several options needed here for POST or similar request, you can simplify it for ‘GET’ request as the module provides a get method for that:

client.get("http://demo.codesamplez.com/", function(response){
    //handling the response
}

Creating HTTPS Request:

To make request over ssl(https), we will just have to import the ‘https’ module instead of ‘http’ and we should be just fine.

var client       = require('https');

However, this client will only works for valid and trusted signed ssl certificates. Self signed ones won’t work and we will get error. If you are interested to get those invalid certificates working too, you will have to add the following line, before making request:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

This will disable the strict mode for unauthorized rejection.

Proxying An Incoming Request:

If you are working on a nodejs server application which might need to forward an incoming request to another remote server and send back the response, without doing all thing coding yourself, you can simply use the node-http-proxy library, which will make our task as simple as:

var http = require('http');
var httpProxy = require('http-proxy');

var server = http.createServer(function(req, res) {
   httpProxy.createProxyServer({}.web(req, res, { target: 'http://other-host.tld:port' });
}).listen(8080);

Final Words:

If you are interested doing some authentication operation with third-party provider via oAuth2 service, then you can also look at this nodejs oAuth2 library to get started. If you having any issue with the nodejs http request code examples given above, let me know via comments. Happy programming 🙂

Related

Filed Under: Programming Tagged With: http, javascript, nodejs

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Comments

  1. MikeC711 says

    September 17, 2015 at 9:47 am

    Nice example. I’m probably doing something silly but, I have my req.end() but the code AFTER it gets executed before the actual request (I’m guessing while node.js is actually waiting for the response). Is there some way to say … run synchronously here … or wait until I hear back? The http request IS running and it is successful, but I respond to the client/caller before I get the actual data. I thought that the end() would sync it all up.

    Reply
  2. niam says

    December 12, 2015 at 11:01 am

    nice article, it help me to develop my internet of things project

    Reply
  3. Mayank Patel says

    December 20, 2015 at 3:36 pm

    Very simple and just what i wanted…

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • How To Work With CodeIgniter Pagination
  • LinQ To SQL Database Update Operations In C#
  • Utilizing Config File In C#.NET Application
  • Get Facebook C# Api Access Token
  • How To Work With Multithreaded Programming In C#.NET Application

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 · Streamline Pro Theme on Genesis Framework · WordPress · Log in