The wix-fetch Module as the Way to Take Your Website to the Next Level

Written by velo | Published 2021/04/05
Tech Story Tags: javascript | software-development | backend | web-development | website-development | wix | beginners | coding-with-velo

TLDR The Fetch API can be used in public and backend code for fetching resources from 3rd party services using HTTPS. The API is an implementation of the standard Javascript Javascript Fetch function. The implementation differs slightly depending on where it's being used. Common errors when using the fetch() function are described here along with possible solutions. Certain CORS (Cross-Origin Resource Sharing) requests are restricted when originating from a browser. To fix this issue you can either use the HTTPS protocol to fetch the requested resources or you can turn off SSL.via the TL;DR App

An implementation of the standard Javascript Fetch API which can be used in public and backend code for fetching resources from 3rd party services
using HTTPS. Learn more.
Guides (Additional information about this section)
Functions (Perform actions on an object)
  • fetch( ) : Retrieves the specified resource from the network using HTTPS.
  • getJSON( ) : Retrieves the specified JSON resource from the network using HTTPS.
Subcategories
  • WixFetchResponse : An object returned by the fetch() function representing an HTTP response to a fetch.
Related Content

Introduction

To make a request, call the fetch() function with the path to a resource and the optional
WixFetchRequest
options. The function returns a promise that resolves to a
WixFetchResponse
. The response object contains a number of properties and functions for retrieving the response's information.
The Fetch API can be used in your front-end or backend code.
To use the Fetch API in the backend, import the
fetch
function from the
wix-fetch
module:
import {fetch} from 'wix-fetch';
The implementation of the Fetch API differs slightly depending on where it's being used. The features documented here comprise the base functionality for both implementations. However, each implementation contains additional features:
In public files, the native browser's Fetch API is used.In backend files the node-fetch module is used.

fetch( )

Retrieves the specified resource from the network using HTTPS.
Description
The
fetch()
function fetches an HTTPS resource from the network. It returns a Promise that resolves to a
WixFetchResponse
object representing the HTTP response to the request.
Responses with an HTTP status code in the ranges 2xx, 4xx, and 5xx are
considered fulfilled. Use the
httpResponse.ok
property to confirm that the HTTP request was successful with a response code in the 2xx range.
The optional
WixFetchRequest
object contains information about an HTTPS request. Additional functionality is available in each of the respective Fetch API implementations.
Notes:
Some common errors when using the
fetch()
function are described here along with possible solutions.
1. You can usually tell if you are experiencing these issues by checking your browser's console using the browser's developer tools.
2. Certain CORS (Cross-Origin Resource Sharing) requests are restricted when originating from a browser. Usually, GET requests and certain POST requests can be made from your site's Public, Page, or Site code. All other requests need to be made from your site's Backend code. If you are experiencing an issue with a
fetch()
call due to a CORS restriction, move the fetch() call to the backend as described in Accessing 3rd Party Services.
3. You cannot request HTTP content if your site is an HTTPS site. To fix this issue you can either use the HTTPS protocol to fetch the requested resources or you can turn off SSL on your site.
Syntax
function fetch(url: string, [options: WixFetchRequest]): Promise<WixFetchResponse>
fetch Parameters
Get a resource
import {fetch} from 'wix-fetch';

// ...

fetch("https://someapi.com/api/someendpoint", {"method": "get"})
  .then( (httpResponse) => {
    if (httpResponse.ok) {
      return httpResponse.json();
    } else {
      return Promise.reject("Fetch did not succeed");
    }
  } )
  .then(json => console.log(json.someKey))
  .catch(err => console.log(err));
Post data to a resource
import {fetch} from 'wix-fetch';

// ...

fetch( "https://someapi.com/api/someendpoint", {
  "method": "post",
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  "body": "somekey=somevalue"
} )
  .then( (httpResponse) => {
    if (httpResponse.ok) {
      return httpResponse.json();
    } else {
      return Promise.reject("Fetch did not succeed");
    }
  } )
  .then( (json) => console.log(json.someKey) )
  .catch(err => console.log(err));
Get a resource and the response information
import {fetch} from 'wix-fetch';

// ...

fetch("https://someapi.com/api/someendpoint", {"method": "get"})
  .then( (httpResponse) => {
    let url = httpResponse.url;
    let statusCode = httpResponse.status;
    let statusText = httpResponse.statusText;
    let headers = httpResponse.headers;
    let bodyUsed = httpResponse.bodyUsed;
    if (httpResponse.ok) {
      return httpResponse.json();
    }
    else {
      return Promise.reject("Fetch did not succeed");
    }
  } )
  .then( (json) => {
    console.log(json.someKey);
  } )
  .catch( (err) => {
    console.log(err);
  } );
Returns
Fulfilled - The HTTP response of the fetch operation.
Rejected - The error that caused the rejection.
Return Type: Promise<WixFetchResponse>

getJSON( )

Retrieves the specified JSON resource from the network using HTTPS.
Description
The
getJSON()
function retrieves a JSON resource from the network. It returns a Promise that resolves to a JSON object representing the response to the request.
To use
getJSON
, import it from
wix-fetch
:
import {getJSON} from 'wix-fetch';
Retrieving the JSON object is performed using the GET method, regardless of what is specified in the
options
parameter.
The
Accept
header is assumed to be
application/json
by default, but you can override it by explicitly setting a different value for
Accept
.
The optional
WixFetchRequest
object contains information about an HTTPS request. Additional functionality is available in each of the respective Fetch API implementations.
Notes:
Some common errors when using the
getJSON()
function are described here along with possible solutions.
1. You can usually tell if you are experiencing these issues by checking your browser's console using the browser's developer tools.
2. Certain CORS (Cross-Origin Resource Sharing) requests are restricted when originating from a browser. Usually, GET requests and certain POST requests can be made from your site's Public, Page, or Site code. All other requests need to be made from your site's Backend code. If you are experiencing an issue with a
getJSON()
call due to a CORS restriction, move the
getJSON()
call to the backend as described in Accessing 3rd Party Services.
3. You cannot request HTTP content if your site is an HTTPS site. To fix this issue you can either use the HTTPS protocol to fetch the requested resources or you can turn off SSL on your site.
Syntax
function getJSON(url: string, [options: WixFetchRequest]): Promise<Object>
getJSON Parameters
Get a JSON resource
import {getJSON} from 'wix-fetch';

// ...

getJSON("https://someapi.com/api/someendpoint")
  .then(json => console.log(json.someKey))
  .catch(err => console.log(err));
Returns
Fulfilled - The JSON response of the fetch operation.
Rejected - The error that caused the rejection.
Return Type: Promise<Object>

Written by velo | Velo is a full-stack development platform that empowers you to rapidly build, manage and deploy professional web apps.
Published by HackerNoon on 2021/04/05