
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 🙂
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.
nice article, it help me to develop my internet of things project
Very simple and just what i wanted…