By Nicholas Brown – Follow me on Twitter.
Writing an app frequently involves Internet connectivity, and ‘GET’ requests are often part of that. HTTP GET requests are a standard way of obtaining data from a server. This article shows you how to send a GET request from your Node.js app to another server.
An example (and common) use case of this is to download data such as weather data, exchange rates, or anything else from an API to incorporate into your own app (be sure to read the API’s terms and conditions!).
This article uses the ‘request-promise’ library to send the GET request.
Before proceeding, install the library with npm:
npm install request-promise
You can also try executing the request on a known domain such as kompulsa.com or Google and it will return the contents of the front page (primarily HTML).
Node.js GET Request Example
The sample code below will send a GET request to providerdomain.com/endpoint. ‘endpoint’ is the endpoint, which could be an API endpoint that provides data or it could just be a webpage. Store this code in a file called rptest.js.
const reqpromise = require('request-promise'); const options = { method: 'GET', //This specifies the type of HTTP request uri: 'https://providerdomain.com/endpoint', //Where the request is sent. json: true, //Specifying that the format is JSON. gzip: true }; reqpromise(options).then(response => { //Execute the request console.log(response); //Print the server’s response to the screen. Executed if there is a response. }).catch((err) => { console.log('API call error:', err.message); }); console.log("Asynchronous test"); //Will be executed before the code above, because the code above is asynchronous
The function starting at ‘Execute the request’ is asynchronous, meaning that execution of your program will continue while it is waiting for the server to respond. This is useful because it won’t freeze your app while waiting for a response.
Bear in mind that if you need to prevent the code after this function from executing until a response has been received — you will need to rewrite it in a synchronous manner. To see it in action, run nodejs rptest.js and you should see something like this if it’s a web page (truncated):
$ nodejs rptest.js Asynchronous test <!doctype html > <!--[if IE 8]> <html class="ie8" lang="en"> <![endif]--> <!--[if IE 9]> <html class="ie9" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html lang="en-GB"> <!--<![endif]--> <head>