Have you seen all of the free code samples available on our Marketplace?

NativeScript Core

Fetch

The Fetch module allows submitting GET and POST requests to a remote server. The module provides functionality for handling content with different formats(String values, JSON objects, FormData content).

Get

The example demonstrates different ways, how we could receive content from a server while making HTTP GET request.

Get requests response body as a string value.

fetch("https://httpbin.org/get")
.then((response) => response.text())
.then((r) => {
    viewModel.set("getStringResult", r);
}).catch((e) => {
});

Get JSON object response and to access the available data in it.

fetch("https://httpbin.org/get")
.then((response) => response.json())
.then((r) => {
}).catch((err) => {
});

Get the fetch result as a FormData.

fetch("https://httpbin.org/get")
.then((result) => result.formData())
.then((response) => {
})
.catch((e) => {
});

With fetch we can make a request and check the response status code by accessing status property.

fetch("https://httpbin.org/get").then((response) => {
}).catch((err) => {
});

The example demonstrates, how to get the request-response header and how to access the available data in it.

fetch("https://httpbin.org/get")
.then((r) => r.json())
.then((response) => {
}).catch((e) => {
});

Improve this document

Demo Source


Post

The example shows how to create POST request while using NativeScript fetch.

fetch("https://httpbin.org/post", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
        username: vm.get("user"),
        password: vm.get("pass")
    })
}).then((r) => r.json())
    .then((response) => {
        const result = response.json;
    }).catch((e) => {
    });

Improve this document

Demo Source