Vue HTTP 请求
HTTP 请求是客户端和服务器之间通信的一部分。
客户端向服务器发送一个HTTP 请求,服务器处理该请求并返回一个 HTTP 响应。
HTTP
HTTP 是HyperTextTransferProtocol(超文本传输协议)的缩写。
当我们浏览互联网时,我们的浏览器一直在后台发送 HTTP 请求。当我们访问一个网页时,我们的浏览器(客户端)会发送多个 HTTP 请求,让服务器将我们想要的页面以及所有相关文件和数据作为 HTTP 响应发送给我们。
最常见的 HTTP 请求类型是 POST
、GET
、PUT
、PATCH
和 DELETE
。在我们HTTP 请求方法页面上了解更多关于不同类型的 HTTP 请求。
在我们HTTP 是什么页面上了解更多关于 HTTP 的信息。
‘fetch’ 方法
要在 Vue 中从服务器获取数据,我们可以使用 JavaScript 的 fetch()
方法。
在本教程中使用 fetch()
方法时,我们不会指定 HTTP 请求方法,这意味着默认使用的请求方法是 GET
。
fetch()
方法需要一个 URL 地址作为参数,这样它才知道从哪里获取数据。
这是一个简单的例子,它使用 fetch()
方法发送一个 HTTP GET
请求,并以 HTTP 响应接收数据。本例中请求的数据是本地文件 file.txt
中的文本。
示例
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>
运行示例 »
在上面的示例中,我们只得到 "[object Promise]" 作为结果,但这并不是我们想要的。
我们得到这个结果是因为 fetch()
是一个基于 Promise 的方法,它返回一个 Promise 对象。因此,fetch()
方法第一次返回的只是一个对象,表示 HTTP 请求已被发送。这是“pending”(待定)状态。
当 fetch()
方法实际获取到我们想要的数据时,Promise 就会 fulfilled(已完成)。
要等待响应 fulfilled 并获得我们想要的数据,我们需要在 fetch()
方法前面使用 await
操作符。
const response = await fetch("file.txt");
当 await
操作符在方法内使用时,该方法需要使用 async
操作符进行声明。
async fetchData() {
const response = await fetch("file.txt");
this.data = response;
}
async
操作符告诉浏览器该方法是异步的,这意味着它会等待某些事情发生,并且浏览器在等待方法完成时可以继续执行其他任务。
现在我们得到的是一个“Response”(响应),而不是一个“Promise”(Promise),这意味着我们离获取 file.txt
文件中的实际文本又近了一步。
示例
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>
运行示例 »
要获取 file.txt
文件中的文本,我们需要在响应上使用 text()
方法。由于 text()
方法是基于 Promise 的方法,我们需要在它前面使用 await
操作符。
终于!现在我们拥有了使用 fetch()
方法从 file.txt
文件中获取文本所需的一切。
示例
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>
运行示例 »
从 JSON 文件获取数据
在上一个示例中,我们从 .txt
文件中获取了文本。但是数据有很多存储方式,现在我们将看到如何从 .json
文件中获取信息。
JSON
是一种常见的文件格式,易于使用,因为它将数据存储为文本,便于人类阅读,并且 JSON
格式也得到了编程语言的广泛支持,因此我们可以,例如,指定要从 .json
文件中提取什么数据。
要从 .json
文件读取数据,我们只需要对上面的示例进行一个更改,就是获取一个 .json
文件,并在响应上使用 json()
方法而不是 text()
方法。
json()
方法读取 HTTP 请求的响应并返回一个 JavaScript 对象。
我们在这里使用 <pre>
标签来显示 JSON
格式的文本,因为它保留了空格和换行符,使其更易于阅读。
示例
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>
运行示例 »
由于 json()
方法的结果是一个 JavaScript 对象,我们可以修改上面的示例来显示 bigLandMammals.json
文件中的一个随机动物。
示例
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>
运行示例 »
来自 API 的数据
API 是 Application Programming Interface(应用程序编程接口)的缩写。您可以在此处了解更多关于 API 的信息。
我们可以连接并使用许多有趣的免费 API,以获取天气数据、股票交易所数据等。
当我们使用 HTTP 请求调用 API 时,我们收到的响应可以包含各种数据,但通常以 JSON
格式包含数据。
示例
可以单击一个按钮从 random-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>
运行示例 »
我们可以稍微修改之前的示例,以便以更友好的方式包含随机用户。
示例
当按钮被点击时,我们会在 <pre>
标签中显示随机用户的姓名、职位和图片。
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>
运行示例 »
使用 'axios' 库在 Vue 中进行 HTTP 请求
'axios' JavaScript 库也允许我们进行 HTTP 请求。
要创建示例并在您自己的机器上运行它,您需要先在项目文件夹中使用终端安装 'axios' 库,如下所示:
npm install axios
这是我们在 Vue 中使用 'axios' 库获取随机用户的方法。
示例
与之前的示例相比,只进行了少量更改,以便使用 'axios' 库而不是其他方法进行 HTTP 请求。
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.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>
运行示例 »