Was this helpful?
- Getting started [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
- Manage types
- Global context and isolation
- Manage apps
- Batch actions with app items
- Manage external services
- Scripts in widgets
- Web components
- Access permissions
- Getting started with processes
- Getting started with signatures
- Getting started with file previews
- Getting started with the organizational chart
- Getting started with users and groups
-
Getting started with the
Table data type - Use cases
- API
In this article
Work with external services
To establish integrations with external services, you can use the fetch function in scripts. It uses the native Fetch API in the browser and a polyfill on the server, so its interface combines features available to them.
The On-Premises server can be located behind a proxy. In this case, it is necessary to specify the parameters of the proxy in the system server’s environment variables
HTTP_PROXYandHTTPS_PROXYto work with external services.Read more about it in the Install BRIX to MicroK8s behind a proxy article in the Help Center.
Example of using
fetch():const res = await fetch('https://my.server/api/products', { method: 'POST', headers: { Authorization: 'Bearer SOME-TOKEN-HERE', }, body: JSON.stringify({ name: 'New product', cost: 13.20, }) }); if (!res.ok) { // Processing an error with a response code ≥ 300 } const product = await res.json();A simple GET request can be done without passing additional parameters:
const res = await fetch(`https://my.server/api/products/${ Context.data.itemId }`);As the request’s parameters, you can pass the request’s method FetchRequest.method, the request’s headers FetchRequest.headers as a simple object Record<string, string> and the request’s body FetchRequest.body as a string.
More about fetch()
JavaScript can send network requests to the server and load new information whenever it’s needed.
For example, we can use a network request to:
There’s an umbrella term “AJAX” (abbreviated Asynchronous JavaScript And XML) for network requests from JavaScript. We don’t have to use XML though: the term comes from old times, that’s why that word is there. You may have heard that term already.
There are multiple ways to send a network request and get information from the server.
The
fetch()method is modern and versatile, so we’ll start with it. It’s not supported by old browsers (can be polyfilled), but very well supported among the modern ones.The basic syntax is:
let promise = fetch(url, options)url– the URL to access.options– optional parameters: method, headers etc.Without
options, this is a simple GET request, downloading the contents of theurl.The browser starts the request right away and returns a promise that the calling code should use to get the result.
Getting a response is usually a two-stage process.
**First, the promise, returned by fetch, resolves with an object of the built-in Response class as soon as the server responds with headers. **
At this stage we can check HTTP status, to see whether it is successful or not, check headers, but don’t have the body yet.
The promise rejects if the
fetchwas unable to make HTTP-request, e.g. network problems, or there’s no such site. Abnormal HTTP-statuses, such as 404 or 500 do not cause an error.We can see HTTP-status in response properties:
status– HTTP status code, e.g. 200.ok– boolean, true if the HTTP status code is 200-299.For example:
Second, to get the response body, we need to use an additional method call.
Responseprovides multiple promise-based methods to access the body in various formats:response.text()– read the response and return as text,response.json()– parse the response as JSON,response.arrayBuffer()– return the response asArrayBuffer(low-level representation of binary data).For instance, let’s get a JSON-object with latest commits from GitHub:
let url = 'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits'; let response = await fetch(url); let commits = await response.json(); // read response body and parse as JSON alert(commits[0].author.login);``` Or, the same without await, using pure promises syntax: ```js fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits') .then(response => response.json()) .then(commits => alert(commits[0].author.login));To get the response text, await
response.text()instead of.json():let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits'); let text = await response.text(); // read response body as text alert(text.slice(0, 80) + '...');** Important: We can choose only one body-reading method.**
If we’ve already got the response with
response.text(), thenresponse.json()won’t work, as the body content has already been processed.let text = await response.text(); // response body consumed let parsed = await response.json(); // fails (already consumed)Response headers
The response headers are available in a Map-like headers object in
response.headers.It’s not exactly a Map, but it has similar methods to get individual headers by name or iterate over them:
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits'); // get one header alert(response.headers.get('Content-Type')); // application/json; charset=utf-8 // iterate over all headers for (let [key, value] of response.headers) { alert(`${key} = ${value}`); }Request headers
To set a request header in
fetch, we can use theheadersoption. It has an object with outgoing headers, like this:let response = fetch(protectedUrl, { headers: { Authentication: 'secret' } });…But there’s a list of forbidden HTTP headers that we can’t set:
Accept-Charset,Accept-EncodingAccess-Control-Request-HeadersAccess-Control-Request-MethodConnectionContent-LengthCookie,Cookie2DateDNTExpectHostKeep-AliveOriginRefererTETrailerTransfer-EncodingUpgradeViaProxy-*Sec-*These headers ensure proper and safe HTTP, so they are controlled exclusively by the browser.
POST requests
To make a
POSTrequest, or a request with another method, we need to use fetch options:method– HTTP method, e.g.POST,body– the request body, one of:FormDataobject, to submit the data asmultipart/form-data.The JSON format is used most of the time.
For example, this code submits
userobject as JSON:let user = { name: 'John', surname: 'Smith' }; let response = await fetch('/article/fetch/post/user', { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify(user) }); let result = await response.json(); alert(result.message);Please note, if the request
bodyis a string, thenContent-Typeheader is set totext/plain;charset=UTF-8by default.But, as we’re going to send JSON, we use
headersoption to sendapplication/jsoninstead, the correctContent-Typefor JSON-encoded data.Sending a file
We can also submit binary data with
fetchusingFormDataandArrayBufferobjects.async function submit() { let data_req = await fetch('/external/data/to/load'); let buffer = await data_req.arrayBuffer(); let form = new FormData(); form.append('file', buffer, 'filename.ext'); let response = await fetch('/article/fetch/post/file', { method: 'POST', body: form }); // the server respond with a confirmation and the size of the image let result = await response.json(); alert(result.message); }Please note, here we don’t set
Content-Typeheader manually because it is automatically set inmultipart/form-data.Summary
A typical
fetchrequest consists of twoawaitcalls:let response = await fetch(url, options); // resolves with response headers let result = await response.json(); // read body as jsonOr, without
await:fetch(url, options) .then(response => response.json()) .then(result => /* process result */)Response properties:
response.status– HTTP code of the response,response.ok–trueif the status is 200-299.response.headers– Map-like object with HTTP headers.Methods to get response body:
response.text()– return the response as text,response.json()– parse the response as JSON object,response.arrayBuffer()– return the response asArrayBuffer(low-level binary data).