Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Use The HTTP Module Instead Of Fetch In NativeScript

Not too long ago I wrote about using the NativeScript fetch module for making HTTP requests in an Android and iOS mobile application. Personally I find that the fetch module is a bit awkward to use, so this time we’re going to take a look at using the http module instead.

The great thing about the NativeScript http module is that it is pretty much the same as it is in the other languages.

Let’s start like we always do, and create a fresh NativeScript project:

tns create ExampleProject
cd ExampleProject
tns platform add ios
tns platform add android

It is important to note that if you’re not using a Mac you cannot add and build for the iOS platform.

For this example, to save us from having to create our own RESTful API, we’re going to make use of a free service by httpbin.org. It will allow us to make sample GET and POST requests.

Let’s take a look at the following request:

GET httpbin.org/ip

{
    "origin": "127.0.0.1"
}

When making a GET request against the service we will receive our public IP in the response. If we make a POST request against the following URL we get something different back:

POST httpbin.org/post

{
  "args": {},
  "data": "{\n    \"firstname\": \"Nic\",\n    \"lastname\": \"Raboy\"\n}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "en-US,en;q=0.8",
    "Cache-Control": "no-cache",
    "Content-Length": "51",
    "Content-Type": "application/json",
    "Host": "httpbin.org",
    "Origin": "chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop",
    "Postman-Token": "3a393452-71aa-38a3-5e81-ab6c819ae0ec",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36"
  },
  "json": {
    "firstname": "Nic",
    "lastname": "Raboy"
  },
  "origin": "50.184.197.236",
  "url": "http://httpbin.org/post"
}

Now that we know how our test service works, lets take a look at how to do this with NativeScript.

We’re going to start by adding some code to the app/main-page.js file of our project:

var http = require("http");

After we’ve included the module we can start using it. A GET request would look something like the following:

exports.getRequest = function() {
    http.getJSON("http://httpbin.org/ip").then(function(result) {
        console.log(JSON.stringify(result));
    }, function(error) {
        console.error(JSON.stringify(error));
    });
}

Notice the use of http.getJSON. We are expecting JSON in our response when we use this command.

Now for the POST request. Go ahead and add the following method to the app/main-page.js file:

exports.postRequest = function() {
    http.request({
        url: "https://httpbin.org/post",
        method: "POST",
        headers: { "Content-Type": "application/json" },
        content: JSON.stringify({ firstname: "Nic", lastname: "Raboy" })
    }).then(function(result) {
        console.log(JSON.stringify(result));
    }, function(error) {
        console.error(JSON.stringify(error));
    });
}

The body, or content, in this case has to be a string. We’re sending the content with the JSON header, so we can just serialize a JSON object with JSON.stringify.

More information on the NativeScript http module can be found in the official documentation.

With our JavaScript logic in place, it is time to look at the front-end XML. Open the project’s app/main-page.xml file and change it to look like the following:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded">
    <StackLayout>
        <Button text="GET Request" tap="getRequest" />
        <Button text="POST Request" tap="postRequest" />
    </StackLayout>
</Page>

Pretty simple front-end here. Just two buttons, one calling our getRequest function and the other calling our postRequest function.

Conclusion

You just saw an alternative to the fetch module in NativeScript. I personally prefer the http module because it resembles the technologies like Angular that I use more frequently. Both will do the job and are incredibly useful in application development since all apps that you find contact remote servers via RESTful calls.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.