Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vue
javascript

How to make HTTP requests in Vue.js using fetch API

Shubham Singh Kshatriya

Overview

When building a web application, there are times when we want to make HTTP requests to get or post data to a web server or API. There are many ways to achieve this, and one of them is using the fetch API.

This shot will show how to make HTTP requests in Vue.js using this API.

Example

In this example, we'll make a simple HTTP GET request on this URL using the fetch API. We'll then show the fetched data if the request is successful. Otherwise, we'll show the error message in the UI.

Now, let's jump to the code.

Code

* {
  margin: 0;
  padding: 0;
}

button {
  margin: 4px;
  border: none;
  border-radius: 5px;
  background-color: rgb(12, 2, 118);
  color: white;
  font-size: 15px;
  padding: 7px 21px;
  font-weight: 500;
  cursor: pointer;
}

.card {
  width: 200px;
  padding: 4px 10px;
  margin: 5px;
  border: 1px solid rgb(245, 209, 100);
  border-radius: 5px;
  background-color: rgb(243, 232, 198);
}

Explanation

In the file Example.vue, we do the following:

  • Line 3: We create a button to get the products. When clicked, it invokes the getProducts() method.
  • Lines 5–9: We iterate over the products array and render each product in the DOM. This will only occur if the products array is not empty.
  • Line 11: We render the error message in the DOM, if there is one. This will only occur if our HTTP request fails due to any reason.
  • Line 15: We import the Example.js script.
  • Line 17: We import the Example.css stylesheet.

In the file Example.js, we do the following:

  • Lines 2–7: We define and initialize the required variables inside the data() function.
  • Lines 9–18: We create a function getProducts() that makes an HTTP GET request. If the request fails, it stores the error in the error variable. Otherwise, it stores the data in the products variable.

In the file Example.css, we do the following:

  • We add some styling for card and the button.

Output

On clicking the "Get Products" button, an HTTP GET request is made. If the request is successful, the fetched data will be shown in the UI. Otherwise, the error message will be shown in the UI.

RELATED TAGS

vue
javascript

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring