HTTP requests (Fetch API)

Version compatibility

This feature was introduced in version 4.6 of the JourneyApps Container.

HTTP on iOS disabled from v4.27

Note: In 2016 Apple announced a security feature for iOS called Application Transport Security (ATS). This feature will eventually enforce HTTPS for all network requests. Although the JourneyApps Container already uses HTTPS for all communications with the JourneyApps Backend, it was still possible for a developer to use the fetch() function to create insecure HTTP requests.

We've activated ATS on our iOS Containers from v4.27, disabling the ability to create HTTP requests.

The Fetch API allows apps to make HTTP Requests to external web services directly from the user's device. This is especially useful for use cases involving "live lookups" on external web services which are required as part of the app workflow. An example would be doing a credit check in the app before allowing the user to continue in issuing a quote for a financial product.

The Fetch API implementation is Promise based. It is based on the WHAT-WG Fetch API specification.

All outgoing requests are subject to Cross Origin Resource Sharing (CORS) restrictions.

Furthermore, there are two important caveats:

  • The Promise returned from fetch() won't reject on an HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on a network failure, or if anything prevented the request from completing.

  • By default, fetch() won't send any cookies to the server, resulting in unauthenticated requests if the site relies on maintaining a user session.

Usage

Here are examples of how to use the fetch() in an app:

GET

Here is an example of a GET request where the response in displayed in a dialog:

var url = 'https://httpbin.org/get?message=hello%20world';
return fetch(url, {})
  .then(function(response) {
// Parse JSON from the body
    return response.json()
  })
  .then(function(jsonData) {
    dialog('Your message', jsonData.args.message);
  });

POST

Here is an example of a simple POST where the response in displayed in a dialog:

var url = 'https://httpbin.org/post';
var payload = {"message": "Hello world"};
var options = {
  method: 'POST',
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(payload)
};

return fetch(url, options)
  .then(function(response) {
// Parse JSON from the body
    return response.json()
  })
  .then(function(jsonData) {
    dialog('You sent:', jsonData.data);
  });

Basic Authentication

fetch.Auth provides helper functions for basic and token authorization headers. For example, the basic helper correctly format encodes the username and password into a valid Authorization header:

var url = 'https://httpbin.org/get';
var options = {
  headers: {
    'Authorization': fetch.Auth.basic('user123','password123')
  }
}
return fetch(url, options)
  .then(function(response) {
    return response.text()
  })
  .then(function(rawBody) {
// httpbin.org/get echos the request details in the response body.
    dialog('Your request:', rawBody);
  });

Network errors

As mentioned before, the fetch promise will be rejected only for network errors. Use .caught (compatibility alias for .catch) or .then(null, handler)

return fetch('invalid')
    .then(null, function(error) {
        // error is a TypeError
        dialog('Unable to connect to the internet')
    });

HTTP errors

The code can check for 2xx HTTP response codes by using response.ok. It is recommended to do this in every response handler.

return fetch('invalid')
  .then(function(response) {
    if (!response.ok) {
// response.status is 404 or 500 or some failure status
      var error = new Error(response.statusText)
      error.response = response
      throw error;
    }

// Status is 2xx (success) - handle it here.
  })
  .caught(function(err) {
// Do something with the error
    dialog('Unable to fulfill the request due to error');
  });

Further Reading

Last updated