Categories
Vue

Make HTTP Requests in a Vue App with Fetch

Spread the love

The Fetch API is an HTTP client that is built into modern browsers.

Therefore, we can use it to make HTTP requests without installing anything.

In this article, we’ll look at how to make requests with the Fetch API in a Vue app.

Making Requests

We can make requests with the fetch function.

For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
export default {
  name: "App",
  async beforeMount() {
    const res = await fetch("https://jsonplaceholder.typicode.com/posts/1", {
      method: "GET",
      mode: "cors"
    });
    const data = await res.json();
    console.log(data);
  }
};
</script>

to make a simple GET request with fetch .

The first argument is the URL.

And the 2nd is an object with the method and mode properties.

The method property is the request method.

The mode is set to 'cors' to let us make cross-origin requests.

To make a POST request, we can rite:

<template>
  <div id="app"></div>
</template>
<script>
export default {
  name: "App",
  async beforeMount() {
    const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        title: "foo",
        body: "bar",
        userId: 1
      })
    });
    const data = await res.json();
    console.log(data);
  }
};
</script>

We set the headers property to set the request headers.

The body property has the stringified JSON object used for the request body.

Uploading a File

To upload a file, we can write:

<template>
  <div id="app">
    <input type="file" @change="onChange">
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    async onChange(ev) {
      const formData = new FormData();
      formData.append("username", "abc123");
      formData.append("avatar", ev.target.files[0]);
      const res = await fetch(
        "https://run.mocky.io/v3/c5189845-2a93-49aa-85c7-70bc64e8af90 ",
        {
          method: "PUT",
          body: formData
        }
      );
      console.log(res);
    }
  }
};
</script>

We have a file input and a change event listener to listen for file selection changes.

The onChange method is the change listener.

And in it, we create a FormData instance and add the file to it with the ev.target.files[0] file object.

Then we make the request by setting the body property to the formData object.

For example, we can write:

<template>
  <div id="app">
    <input type="file" @change="onChange" multiple>
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    async onChange(ev) {
      const formData = new FormData();
      formData.append("username", "abc123");
      for (const file of ev.target.files) {
        formData.append("photos", file);
      }
      const res = await fetch(
        "https://run.mocky.io/v3/c5189845-2a93-49aa-85c7-70bc64e8af90 ",
        {
          method: "PUT",
          body: formData
        }
      );
      console.log(res);
    }
  }
};
</script>

We loop through the ev.target.files object with the for-of loop to add all the files from the object to the request body.

Check if a Request is Successful

We can check if a request is successful by catching the error.

Only network errors are raised. This doesn’t include completed requests with 400 or 500 series error codes.

For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
export default {
  name: "App",
  async beforeMount() {
    try {
      const res = await fetch("https://picsum.photos/200");
      const data = await res.blob();
      console.log(data);
    } catch (error) {
      console.error(error);
    }
  }
};
</script>

to catch the error with the catch block.

Conclusion

We can make HTTP requests in a Vue app with the Fetch API.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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