Axios 是一个基于 promise 的 HTTP 库,本质是XMLHttpRequests请求即ajax请求。
Axios在浏览器端实际上也是基于 XMLHttpRequest 来实现的,并且基于 promise 提供了一套 promise 风格的链式调用 API,支持请求和响应拦截、提供并发请求接口功能、轻量高效、简单易用、客户端支持防止CSRF等优点。也是当前使用最为广泛的类库之一。
一、Axios 基本使用
Axios 提供了两种不同的形式来发送 HTTP 请求,一种是通过 axios() 方法,另一种是分别通过 axios 对象提供的与 HTTP 方法对应的方法来发起请求,如: axios.get() , axios.post() , axios.delete()。
- axios.get(url)
- axios.post(url,data)
- axios.delete(url)
- axios.update(url)
- axios.put(url,data)
上一章的示例代码:
axios
.get("http://localhost:3000/posts")
.then(function (response) {
console.log(response.data);
console.log("-----")
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
})
.catch(function (error) {
console.log(error);
})
请求响应的处理在 then 和 catch 回调中,请求正常会进入 then ,请求异常则会进 catch。
通过 axios 发出请求的响应结果中, axios 会加入一些字段,如图所示:
响应数据简要说明:
{
// `data` 由服务器提供的响应
data: {},
// `status` 来自服务器响应的 HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: 'OK',
// `headers` 是服务器响应头
// 所有的 header 名称都是小写,而且可以使用方括号语法访问
// 例如: `response.headers['content-type']`
headers: {},
// `config` 是 `axios` 请求的配置信息
config: {},
// `request` 是生成此响应的请求
// 在node.js中它是最后一个ClientRequest实例 (in redirects),
// 在浏览器中则是 XMLHttpRequest 实例
request: {}
}
我们在浏览器的控制台查看axios返回的response结果,可以看到axios帮助我们把请求和响应结果都做了一个封装,实际上除了data属性外,其他的属性都是axios为了让我们更好地分析本次网络请求的参数而做的封装,一般来说我们更多是直接使用data中的数据即可。
二、页面输出Axios响应数据
首先,定义一个响应式变量 posts;然后,将axios 调用的响应结果赋值给 posts。
<script setup>
import HelloWorld from './components/HelloWorld.vue'
import axios from 'axios'
import { ref } from 'vue'
const posts = ref([])
const handleClick=()=>{
axios
.get("http://localhost:3000/posts")
.then(function (response) {
posts.value = response.data
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
</script>
在template中,使用 v-for 遍历 posts并进行输出,示例代码如下:
<template>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src="/vite.svg" class="logo" alt="Vite logo" />
</a>
<a href="https://vuejs.org/" target="_blank">
<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
</a>
</div>
<div>
<button v-on:click="handleClick">获取数据</button>
</div>
<div class="posts" v-if="posts.length">
<div v-for="post in posts" :key="post.id">
<h3>{{ post.title }}</h3>
<p>{{ post.author }}</p>
</div>
</div>
<HelloWorld msg="Vite + Vue" />
</template>
本文暂时没有评论,来添加一个吧(●'◡'●)