WebVeta - Advanced, unified, consistent search for your website(s), from content of your website(s), blogs(s). First 50 customers, who sign-up prior to 15/05/2024 get unlimited access to existing features, newer features for at least 1 year. Sign up now! https://webveta.alightservices.com/
Categories
React

React Fetch API

React Fetch API is used for calling REST API’s.

First some sample code and then a lengthy discussion of various options.

const postRequestOptions = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: {}
};

postRequestOptions.body = JSON.stringify(jsonObject);

fetch('/path', postRequestOptions)
.then(response => {console.log(response); return response.json();})
.then(data => console.log(data);

In the above code block we have declared a postRequestOptions object, for POST HTTP method, declared the content type as application/json.

Then we set the body of the postRequestOptions object by representing a json object as a string.

Then we used the fetch API, once the response is returned, we are logging the response, creating a data object from the received response’s json and logging the object to the console.

There are several options for the RequestOptions:

referrer: The referrer can be set

referrer policy: Tells the browser to set the referrer header based on the policy. “strict-origin-when-cross-origin”, “no-referrer-when-downgrade”, “no-referrer”, “origin”, “origin-when-cross-origin”, “same-origin”, “strict-origin”, “unsafe-url”.

mode: “cors”, “same-origin”, “no-cors”

credentials: Whether to send cookies and tokens. “same-origin” – default, “include”, “omit”

cache: “default”, “no-store”, “reload”, “no-cache”, “force-cache”, “only-if-cached”

redirect: “follow” – error, “error”, “manual”. If you want error to be raised for 302, instead of sending another request use “error” or you can know the status by accessing the response.status that provides the HTTP status code.

integrity: SHA256/384/512 of expected hash.

keepalive: true or false, used when you want to do something on window.onunload()

Here is a webpage with a very detailed discussion of the options:

https://javascript.info/fetch-api