How to fetch data with Javascript like a pro

NpN8WH8v6CfA6j7dKAzuoiE5Lit2 db93p6b


of fetch APIs allow you to make HTTP requests so you can do many things with Javascript, such as getting data from the API, sending data to a server, retrieving the entire content of a web page, and more. This HTTP request asynchronously fetches data from the provided URL and produces some kind of HTTP response. Let’s see how it works.

of fetch() function is a global function, most often used to interact with the API. It’s okay if you’re a beginner. fetch() works.

Using fetch in JavaScript

The most basic usage of fetch takes one argument, the URL you want to fetch.ever since fetch You always have to provide a URL to generate an HTTP request.

let fetchExample = fetch("").then((res) => {
    // Do something with res

Fetch results are asynchronous, so you can use then() Catch the response and do something with things about returns res Or the response is that there are many built-in methods that can parse the retrieved content immediately fetch:

  • res.text() – Returns the text content of a URL. For websites, returns HTML.
  • res.json() – Returns formatted JSON data, if any.
  • res.blob() – Returns the blob data if it exists.
  • res.arrayBuffer() – Returns the arrayBuffer data, if any.
  • res.formData() – Returns the formData data, if any.

Since different URLs produce different types of content, the methods above allow you to parse that content in any way you like. Let’s look at two very common examples to understand how it all works.

Example 1: Retrieving website HTML content using Javascript fetch

as mentioned above, res.text() will give you the text content of the URL, so you can use it to get the entire HTML content of the URL. Once you have caught the response using res.text()you can catch another response thencan download and return the content of the provided URL.

let websiteData = fetch("").then(res => res.text()).then((data) => {
    return data;
// Now contains our website's HTML.

If the link does not exist or you get an error, response Object contains an error.For example, pages not found are returned 404or a bad gateway error is returned 502.

Example 2: Retrieving JSON via Javascript Fetch

If the content of the URL consists of JSON, res.json(). For example, the following code returns a JSON object from a URL, assuming the URL is sending back valid JSON.

let apiResponse = fetch("").then(res => res.json()).then((data) => {
    return data;
// Now contains a JSON object - assuming one exists

JavaScript fetch options

It’s also important to understand the options available with fetch. Follows the URL as an object. in short, fetch(URL, { options })If you’ve worked with HTTP requests before, you may find some of them familiar.of fetch The functions shown below include all possible options available.

fetch("", {
    body: JSON.stringify({ someData: "value" })
    method: 'POST'
    mode: 'cors'
    cache: 'no-cache'
    credentials: 'same-origin'
    headers: {
      'Content-Type': 'application/json'
    redirect: 'follow'
    referrerPolicy: 'no-referrer'

And the meaning of each is summarized as follows.

  • body Contains the body of the text. In this example, we are sending JSON that needs to be stringified.
  • mode Indicates whether cross-origin requests are accepted.maybe cors/no-cors/same-origin.
  • cache Refers to how the browser interacts with the cache.maybe default/no-cache/reload/force-cache/only-if-cached.
  • credentials Indicates whether cross-origin cookies should be sent with requests.maybe include/same-origin/omit.
  • headers Contains the headers associated with the request. It can contain arbitrary HTTP headers. For example, here it shows: Content-Type – However, custom HTTP headers can also be used.
  • redirect Determines behavior when the retrieved URL is redirected.maybe follow/error/manual.
  • referrerPolicy Determines the amount of referrer information passed in the request.maybe no-referrer/no-referrer-when-downgrade/origin/origin-when-cross-origin/same-origin/strict-origin/strict-origin-when-cross-origin/unsafe-url.

Remember that JavaScript fetching is asynchronous

With fetch you visit a URL to gather information and response back to us This is not instant, as it takes time to load, download, and restore the URL.If I simply run fetch by itself, the console log immediately after is Promise,not response From the desired URL:

let apiResponse = fetch("");
console.log(apiResponse); // Returns Promise<Pending>

this is, fetch() The function runs, but the Javascript responseSo you have to explicitly tell Javascript to wait for it. response.

2 ways to wait fetch():

  • can be used thenand manipulate our response fetch() internal then().
  • can be used awaitwait for the fetch to return before using its contents.

Wait for fetch in Javascript using then

use then Often used to catch and process responses from fetch.the contents of fetch() can be operated within then() A callback function, but not outside of it. for example:

let apiResponse = fetch("").then(res => res.json()).then((data) => {
    // We can do anything with the data from our api here. 
    return data;
console.log(apiResponse); // This will return Promise<Pending>
                          // That means we can't use the apiResponse variable
                          // outside of the then() function.

If you want to use content from fetch() outside of thenyou should use await.

Wait for fetch using await in Javascript

Another way to wait for fetch is await keyword. Most modern browsers support toplevel, but if you’re worried about support, or using a version of his Node.JS earlier than 14.8, you might want to wrap it. await code in async function.

With await you can use the response from the API anywhere in your function or code. response functions, etc. text() Also json() Moreover. for example:

// Typically we wrap await in an async function
// But most modern browsers and Node.JS support
// await statements outside of async functions now.
async getAPI() {
    let apiResponse = await fetch("");
    let response = apiResponse.json();
    // Since we waited for our API to respond using await
    // The response variable will return the response from the API
    // And not a promise.

If you want to learn more about asynchronous operations, read this Asynchronous Javascript tutorial.


This guide explained how fetching works. I showed you the different options you can send with . fetch() Requests and how to wait for a response using the asynchronous concept in Javascript. fetch() It’s an incredibly powerful tool in Javascript, and it’s used heavily in big products all the time. I hope you enjoyed this article.

. . . comment& more!


Source link

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings

    weebly vs squarespace article image

    Weebly vs Squarespace – Forbes Advisors

    07a6692b shutterstock 1361674454

    JavaScript developers talk about what matters and what’s next