Javascript Fetch: Get/Post/Put/Delete example | DevsDay.ru

IT-блоги Javascript Fetch: Get/Post/Put/Delete example

dev.to 15 октября 2021 г.


JavaScript Fetch API provides an interface for accessing and manipulating HTTP requests and responses. In this tutorial, we will create examples that use Javascript fetch() method to make Get/Post/Put/Delete request. The final section shows a simple Fetch HTTP Client to interact and get data from Rest API in Javascript.

Related Post: Axios Tutorial: Get/Post/Put/Delete request example

Full Article at BezKoder

Javascript Fetch Overview

Javascript Fetch API has a global fetch() method that provides way to fetch resources asynchronously across the network.
fetch() returns a Promise that resolves with a Response object, which is fulfilled once the response is available.

const responsePromise = fetch(resourceUrl [, options]);

A basic fetch request will look like this::

fetch('/bezkoder.com/data')
  .then(response => response.json())
  .then(data => console.log(data));

Javascript Fetch Response Data

The Response object we mention above represents the entire HTTP response, it does not directly contain the response body. To get the actual JSON body of the response, we use following methods:

Javascript Fetch Response Metadata

We can also access metadata such as headers, status, statusText, type, url from the Response object:

fetch('/bezkoder.com/data').then(function(response) {
    console.log(response.headers.get('Content-Type'));
    console.log(response.headers.get('Date'));

    console.log(response.status);
    console.log(response.statusText);
    console.log(response.type);
    console.log(response.url);
});

Fetch error handling

The response Promise does not reject on HTTP errors (for example: 404, 500). It only rejects when encountering a network error. So we must use then() to check for HTTP errors with response.ok status and/or response.status properties.

fetch('/bezkoder.com/data')
  .then(function(response) {
    // if (response.status !== 200)
    if (!response.ok) {
       console.log('Error with Status Code: ' + response.status);
       return;
    }

    response.json().then(function(data) {
      console.log(data);
    });
  })
  .catch(function(err) {
    console.log('Error: ' + err);
  });

Fetch try catch async-await

If you want to use async-await, just wrap the fetch call with try/catch block.

async function getData() {
  try {
    const response = await fetch('/bezkoder.com/data');

    if (!response.ok) {
      const message = 'Error with Status Code: ' + response.status;
      throw new Error(message);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log('Error: ' + err);
  }
}

Fetch with params

You can use URL object with URLSearchParams to set query string params.

let url = new URL('/bezkoder.com/data');
const params = { title: 'web'};
url.search = new URLSearchParams(params);

try {
  const response = await fetch(url);

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}

And this is equivalent:

const response = await fetch('/bezkoder.com/data?title=web');

Fetch with headers

To send Fetch request with Headers, we pass an option object with method and headers property.

const options = {
  method: 'get',
  headers: {
    "Content-Type": "application/json",
    "x-access-token": "token-value",
  }
};

try {
  const response = await fetch('/bezkoder.com/data', options);

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}

Javascript Fetch POST

Fetch POST Form data

Let's create a POST request with Formdata in the body of the request.

let formData = new FormData();
formData.append('title', 'BezKoder Tutorial');
formData.append('description', 'Tut Desc');

try {
  const response = await fetch('/bezkoder.com/data', {
    method: "post",
    // headers: {
    //   "Content-Type": "application/x-www-form-urlencoded"
    // },
    body: formData
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}

If you use application/x-www-form-urlencoded, the keys and values are encoded in key-value tuples.

Fetch POST JSON

Let's create a POST request with JSON.

We use JSON.stringify() on the object before passing it in the body of the request and set application/json for the header Content-Type.

const postData = {
  title: title,
  description: description,
};

try {
  const response = await fetch('/bezkoder.com/data', {
    method: "post",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(postData)
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}

Fetch POST file

Working with file is similar with previous one by using Form data.

let formData = new FormData();
// formData.append('title', 'BezKoder Tutorial');
// formData.append('description', 'Tut Desc');
formData.append('file', file);

try {
  const response = await fetch('/bezkoder.com/data', {
    method: "post",
    body: formData
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}

We don't need to set the Content-Type header with multipart/form-data. The browser will automatically choose the appropriate content type header including form boundary.

Javascript Fetch PUT

Now we're gonna generate Fetch PUT example with JSON data. It's similar to Fetch POST request:

  • method: "put"
  • "Content-Type": "application/json"
  • using JSON.stringify() on the object
const postData = {
  title: title,
  description: description,
};

try {
  const response = await fetch('/bezkoder.com/data', {
    method: "put",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(postData)
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}

Fetch DELETE example

try {
  const response = await fetch('/bezkoder.com/data/42', {
    method: "delete"
  });

  if (!response.ok) {
    const message = 'Error with Status Code: ' + response.status;
    throw new Error(message);
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.log('Error: ' + err);
}

Javascript Fetch example with Rest API

We will build a HTTP Client to make CRUD requests to Rest API in that:

  • Fetch GET request: get all Tutorials, get Tutorial by Id, find Tutorial by title
  • Fetch POST request: create new Tutorial
  • Fetch PUT request: update an existing Tutorial
  • Fetch DELETE request: delete a Tutorial, delete all Tutorials

javascript-fetch-api-tutorial-example

This Fetch Client works with the following Web API:

Methods Urls Actions
POST /api/tutorials create new Tutorial
GET /api/tutorials retrieve all Tutorials
GET /api/tutorials/:id retrieve a Tutorial by :id
PUT /api/tutorials/:id update a Tutorial by :id
DELETE /api/tutorials/:id delete a Tutorial by :id
DELETE /api/tutorials delete all Tutorials
GET /api/tutorials?title=[keyword] find all Tutorials which title contains keyword

You can find step by step to build a Server like this in one of these posts:

For more details, please visit:
https://www.bezkoder.com/javascript-fetch/

Conclusion

With this Javascript Fetch tutorial, you've known many ways to make GET/POST/PUT/DELETE request using Fetch API (with headers, params, body, form data...). You also know how to handle error in Fetch request or use async/await with try/catch statement.

Instead of Fetch API, you can also use Axios which is a promise-based HTTP Client Javascript library for Node.js and Browser. Kindly visit:
Axios Tutorial: Get/Post/Put/Delete request example

Happy Learning! See you again.

Further Reading

You can apply it in one of following React/Vue applications (using fetch instead of axios):

Источник: dev.to

Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.

javascript webdev todayilearned beginners