Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮   
     ❯   

Vue Tutorial

Vue HOMEVue IntroVue DirectivesVue v-bindVue v-ifVue v-showVue v-forVue EventsVue v-onVue MethodsVue Event ModifiersVue FormsVue v-modelVue CSS BindingVue Computed PropertiesVue WatchersVue Templates

Scaling Up

Vue Why, How and SetupVue First SFC PageVue ComponentsVue PropsVue v-for ComponentsVue $emit()Vue Fallthrough AttributesVue Scoped StylingVue Local ComponentsVue SlotsVue v-slotVue Scoped SlotsVue Dynamic ComponentsVue TeleportVue HTTP RequestVue Template RefsVue Lifecycle HooksVue Provide/InjectVue RoutingVue Form InputsVue AnimationsVue Animations with v-forVue BuildVue Composition API

Vue Reference

Vue Built-in AttributesVue Built-in ComponentsVue Built-in ElementsVue Component InstanceVue DirectivesVue Instance OptionsVue Lifecycle Hooks

Vue Examples

Vue ExamplesVue ExercisesVue QuizVue SyllabusVue Study PlanVue ServerVue Certificate

Vue HTTP Requests

TheHTTP request is a part of the communication between a client and a server.

The client sends anHTTP request to the server, which handles the request and returns an HTTP response.

HTTP

HTTP stands forHyperTextTransferProtocol.

Our browser makes HTTP requests all the time in the background when we browse the Internet. When we access an Internet page, our browser (the client) sends several HTTP requests to make the server send us the page we want with all the relevant files and data as HTTP responses.

The most common kinds of HTTP requests arePOST,GET,PUT,PATCH, andDELETE. Learn more about the different kinds of HTTP requests on ourHTTP Request Methods page.

Learn more about what HTTP is on ourWhat is HTTP page.


The 'fetch' Method

To get data from a server in Vue we can use the JavaScriptfetch() method.

When we use thefetch() method in this tutorial we will not specify the HTTP request method, and that means that the default request methodGET is what is used in the background.

Thefetch() method expects a URL address as an argument so that it knows where to get the data from.

Here is a simple example that uses thefetch() method to send an HTTPGET request, and receive data as an HTTP response. The data requested in this case is the text inside the local filefile.txt:

Example

App.vue:

<template>  <div>    <button @click="fetchData">Fetch Data</button>    <p v-if="data">{{ data }}</p>  </div></template><script>export default {  data() {    return {      data: null,    };  },  methods: {    fetchData() {      const response = fetch("file.txt");      this.data = response;    }  }};</script>
Run Example »

In the example above, we only get "[object Promise]" as a result, but that is not what we want.

We get this result becausefetch() is a promised-based method that returns a promise object. The first return thefetch() method gives is therefore just an object which means that the HTTP request has been sent. This is the "pending" state.

When thefetch() method actually gets the data we want, the promise is fulfilled.

To wait for the response to be fulfilled, with the data we want, we need to use theawait operator in front of thefetch() method:

const response = await fetch("file.txt");

When theawait operator is used inside a method, the method is required to be declared with theasync operator:

async fetchData() {  const response = await fetch("file.txt");  this.data = response;}

Theasync operator tells the browser that the method is asynchronous, which means that it waits for something, and the browser can continue to do other tasks while it waits for the method to complete.

Now what we get is a "Response", and no longer just a "Promise", which means we are one step closer to get the actual text inside thefile.txt file:

Example

App.vue:

<template>  <div>    <button @click="fetchData">Fetch Data</button>    <p v-if="data">{{ data }}</p>  </div></template><script>export default {  data() {    return {      data: null,    };  },  methods: {    async fetchData() {      const response = await fetch("file.txt");      this.data = response;    }  }};</script>
Run Example »

To get the text inside thefile.txt file we need to use thetext() method on the response. Because thetext() method is a promise based method, we need to use theawait operator in front of it.

Finally! We now have what we need to get the text from inside thefile.txt file with thefetch() method:

Example

App.vue:

<template>  <div>    <button @click="fetchData">Fetch Data</button>    <p v-if="data">{{ data }}</p>  </div></template><script>export default {  data() {    return {      data: null,    };  },  methods: {    async fetchData() {      const response = await fetch("file.txt");      this.data = await response.text();    }  }};</script>
Run Example »

Fetch Data from a JSON File

In the previous example we fetched text from a.txt file. But there are many ways to store data, and now we will see how we can fetch information from a.json file.

JSON is a common file format that is easy to work with because data is stored as text so that it is easy to read for humans, and theJSON format is also widely supported by programming languages, so that we can, for example, specify what data to extract from a.json file.

To read data from a.json file, the only change we need to do to the example above is to fetch a.json file, and use thejson() method instead of thetext() method on the response.

Thejson() method reads the response from the HTTP request and returns a JavaScript object.

We use the<pre> tag here to show theJSON formatted text because it preserves spaces and line breaks so that it is easier to read.

Example

App.vue:

<template>  <div>    <button @click="fetchData">Fetch Data</button>    <pre v-if="data">{{ data }}</pre>  </div></template><script>export default {  data() {    return {      data: null,    };  },  methods: {    async fetchData() {      const response = await fetch("bigLandMammals.json");      this.data = await response.json();    }  }};</script>
Run Example »

Because the result of thejson() method is a JavaScript object, we can modify the example above to show a random animal from thebigLandMammals.json file:

Example

App.vue:

<template>  <p>Try clicking the button more than once to see new animals picked randomly.</p>  <button @click="fetchData">Fetch Data</button>  <div v-if="randomMammal">    <h2>{{ randomMammal.name }}</h2>    <p>Max weight: {{ randomMammal.maxWeight }} kg</p>  </div></template><script>export default {  data() {    return {      randomMammal: null    };  },  methods: {    async fetchData() {      const response = await fetch("bigLandMammals.json");      const data = await response.json();      const randIndex = Math.floor(Math.random()*data.results.length);      this.randomMammal = data.results[randIndex];    }  }};</script>
Run Example »

Data from an API

API stands forApplicationProgrammingInterface. You can learn more about APIhere.

There are a lot of interesting free APIs we can connect with and use, to get weather data, stock exchange data, etc.

The response we get when we call an API with an HTTP request can contain all kinds of data, but often contains data in theJSON format.

Example

A button can be clicked to get a random user from therandom-data-api.com API.

App.vue:

<template>  <h1>Example</h1>  <p>Click the button to fetch data with an HTTP request.</p>  <p>Each click generates an object with a random user from <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a>.</p>  <p>The robot avatars are lovingly delivered by <a href="http://Robohash.org" target="_blank">RoboHash</a>.</p>  <button @click="fetchData">Fetch data</button>  <pre v-if="data">{{ data }}</pre></template><script>  export default {    data() {      return {        data: null,      };    },    methods: {      async fetchData() {              const response = await fetch("https://random-data-api.com/api/v2/users");         this.data = await response.json();      }       }  };</script>
Run Example »

We can modify our previous example a little bit to include the random user in a more user friendly way:

Example

We show the random user name in a<pre> tag, along with the job title and image when the button is clicked.

App.vue:

<template>  <h1>Example</h1>  <p>Click the button to fetch data with an HTTP request.</p>  <p>Each click generates an object with a random user from <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a>.</p>  <p>The robot avatars are lovingly delivered by <a href="http://Robohash.org" target="_blank">RoboHash</a>.</p>  <button @click="fetchData">Fetch data</button>  <div v-if="data" id="dataDiv">    <img :src="data.avatar" alt="avatar">    <pre>{{ data.first_name + " " + data.last_name }}</pre>    <p>"{{ data.employment.title }}"</p>  </div></template><script>  export default {    data() {      return {        data: null,      };    },    methods: {      async fetchData() {              const response = await fetch("https://random-data-api.com/api/v2/users");         this.data = await response.json();      },        }  };</script><style>#dataDiv {  width: 240px;  background-color: aquamarine;  border: solid black 1px;  margin-top: 10px;  padding: 10px;}#dataDiv > img {  width: 100%;}pre {  font-size: larger;  font-weight: bold;}</style>
Run Example »

HTTP Request in Vue with The 'axios' Library

The 'axios' JavaScript library also allows us to make HTTP requests.

To create and run the example on your own machine you first need to install the 'axios' library using the terminal in your project folder, like this:

npm install axios

This is how we can use the 'axios' library in Vue to fetch a random user:

Example

Only small changes are made to the previous example to do the HTTP request with the 'axios' library instead.

App.vue:

<template>  <h1>Example</h1>  <p>Click the button to fetch data with an HTTP request.</p>  <p>Each click generates an object with a random user from <a href="https://random-data-api.com/">https://random-data-api.com/</a>.</p>  <p>The robot avatars are lovingly delivered by <a href="http://Robohash.org">RoboHash</a>.</p>  <button @click="fetchData">Fetch data</button>  <div v-if="data">    <img :src="data.data.avatar" alt="avatar">    <pre>{{ data.data.first_name + " " + data.data.last_name }}</pre>    <p>"{{ data.data.employment.title }}"</p>  </div></template><script>  import axios from 'axios'  export default {    data() {      return {        data: null,      };    },    methods: {      async fetchData() {              this.data = await axios.get("https://random-data-api.com/api/v2/users");      }    }  };</script><style>#dataDiv {  width: 240px;  background-color: aquamarine;  border: solid black 1px;  margin-top: 10px;  padding: 10px;}#dataDiv > img {  width: 100%;}pre {  font-size: larger;  font-weight: bold;}</style>
Run Example »



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp