• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • 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

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / How To Create HTTP Request In NodeJS

How To Create HTTP Request In NodeJS

September 14, 2014 by Rana Ahsan 3 Comments

nodejs http request

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

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

About Rana Ahsan

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

Reader Interactions

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.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023