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).
Usage
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) => {
});
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) => {
viewModel.set("origin", r.origin);
viewModel.set("url", r.url);
}).catch((err) => {
});
fetch("https://httpbin.org/get")
.then((response) => response.json())
.then((r) => {
viewModel.set("origin", r.origin);
viewModel.set("url", r.url);
}).catch((err) => {
});
Get the fetch result as a FormData.
fetch("https://httpbin.org/get")
.then((result) => result.formData())
.then((response) => {
})
.catch((e) => {
});
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) => {
const status = response.status;
viewModel.set("statusCodeResult", status);
}).catch((err) => {
});
fetch("https://httpbin.org/get").then((response) => {
const status = response.status;
viewModel.set("statusCodeResult", status);
}).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) => {
console.log("Header");
console.log(response);
}).catch((e) => {
});
fetch("https://httpbin.org/get")
.then((r) => r.json())
.then((response) => {
console.log("Header");
console.log(response);
}).catch((e) => {
});
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) => {
});
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) => {
});