Use the form.fetch
method to make arbitrary HTTP requests at runtime. This is similar to the browser Fetch API, but isn't 1:1 compatible.
Here's a simple example that loads in a list of countries from this JSON file:
let url = "https://prod.static.formulate.dev/docs/flags/flags.json";
let response = await form.fetch(url);
let choices = JSON.parse(response.text).map(c => ({value: c.Code, label: c.Name}));
await form.select("What country are you from?", choices, {single: true});
Which generates a form that looks like:
Your Formulate script runs in a secure browser sandbox, and as such some restrictions and caveats apply to the use of fetch
:
string
using the text
key, as demonstrated above. Streaming responses and binary response bodies are not supported at the moment.ok
or status
field in the Response
object in order to be resilient to HTTP errors.In addition to a URL, you can pass an options object to fetch
like so:
await form.fetch('https://example.com/', {method: 'POST'});
Here's a full list of supported options:
Option | Type | |
---|---|---|
method |
string |
The HTTP method to use. One of GET , POST , PUT , DELETE , OPTIONS |
headers |
object |
HTTP request headers |
body |
string |
HTTP request body |
redirect |
string |
Control redirect behavior on a 3xx response. One of follow , error , manual |
referrer |
string |
HTTP Referer |
integrity |
string |
Set the subresource integrity value |
A call to form.fetch()
returns a Response
, which contains:
Option | Type | |
---|---|---|
text |
string |
The response body, serialized to a string |
headers |
object |
HTTP response headers |
url |
string |
The URL of the response |
ok |
boolean |
Indicates whether the response was successful (status in the range 200 – 299) or not |
redirected |
boolean |
Indicates whether or not the response is the result of a redirect |
status |
number |
The status code of the response |
statusText |
string |
The status message corresponding to the status code. (e.g., OK for 200). |
type |
sting |
The type of the response (e.g., basic , cors ). |