前后端数据交互:Axios

Axios 介绍

  在前端页面展示的数据大多数都是通过访问一个API获取的,做这件事的方法有好几种,例如jquery ajax、vue-resource、axios,而vue-resource是vue插件,但3版本不再更新,目前官方推荐主流的axios,aixos是一个http请求库。
官方文档:http://www.axios-js.com/zh-cn/docs/

Axios 安装

1、安装axios:npm install axios
2、在main.js文件中全局注册
3、在组件中使用

//安装axios
npm install axios

//在main.js文件中全局注册
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import Test from "@/components/Test";
import axios from "axios";

//createApp(App).use(router).mount("#app");
const app = createApp(App);
app.use(router).use(router).mount('#app');
app.component('Test', Test)
app.config.globalProperties.$axios=axios

从API获取用户数据,在前端展示:

<template>
  <table border="1px">
    <thead>
    <tr>
      <td>ID</td>
      <td>用户</td>
      <td>邮箱</td>
      <td>性别</td>
      <td>地址</td>
    </tr>
    </thead>
    <tbody v-for="i in username" :key="i.id">
    <tr>
      <td>{{ i.id }}</td>
      <td>{{ i.username }}</td>
      <td>{{ i.email }}</td>
      <td>{{ i.sex }}</td>
      <td>{{ i.city }}</td>
    </tr>
    </tbody>
  </table>
  <button type="button" @click="getData">获取用户信息</button>
</template>
<script>
export default {
  name: "TestUser",
  data(){
    return{
      username: ""
    }
  },methods:{
      getData(){
        this.$axios.get('http://127.0.0.1:8888/api/v1/user') //过去接口数据
            .then(response => (this.username=response.data.data))  //将获取到的数据赋值给
      }
  }
}
可以加created实现打开页面自动加载

Axios发送post请求

<template>
  <form action="#">
    用户名:<input type="text" v-model="form.username">
    密 码:<input type="password" v-model="form.password">
    <button @click="btn">登录</button>
  </form>
  <p style="color: red" v-if="notic">用户名或密码不能为空</p>
</template>

<script>
export default {
  name: "postreq",
  data() {
    return {
      form: {
        username: "",
        password: ""
      },
      notic: false
    }
  },methods: {
    btn(){
      if (this.form.username == "" || this.form.password == ""){
        this.notic = true
      }else{
        this.notic = false
        console.log(this.form)
        this.$axios.post("http://127.0.0.1:8888/api/v1/user", this.form)

      }
    }
    }
}
</script>

<style scoped>

</style>

Axios 异常处理

  很多时候我们可能并没有从API 获取想要的数据。这可能是由于很多种因素引起的,比如axios 调用可能由于多种原因而失败,包括但不限于:
  • API 不工作了;
  • 请求发错了;
  • API 没有按我们预期的格式返回信息。
 可以使用catch异常处理这些问题。
模拟连接一个未存在的地址,前端给出提示:

<template>
  <table border="1px">
    <thead>
    <tr>
      <td>ID</td>
      <td>用户</td>
      <td>邮箱</td>
      <td>性别</td>
      <td>地址</td>
    </tr>
    </thead>
    <tbody v-for="i in username" :key="i.id">
    <tr>
      <td>{{ i.id }}</td>
      <td>{{ i.username }}</td>
      <td>{{ i.email }}</td>
      <td>{{ i.sex }}</td>
      <td>{{ i.city }}</td>
    </tr>
    </tbody>
  </table>
  <button type="button" @click="getData">获取用户信息</button>
</template>
<script>
export default {
  name: "TestUser",
  data(){
    return{
      username: "",
      error: "获取数据失败,请稍后再试"
    }
  },methods:{
      getData(){
        this.$axios.get('http://127.0.0.1:8888/user.json1') //过去接口数据
            .then(response => {this.username=response.data.data})  //将获取到的数据赋值给
            .catch(error =>{
              console.log(error)
            alert(this.error)
            })
      }
  },created() {
    this.getData()
  }
}

</script>

<style scoped>

Axios 全局默认值

  在开发中,几乎每个组件都会用到axios发起数据请求,如果每次都填写完整的请求路径,不利于后期维护。这时可以设置全局axios默认值。
在main.js里定义

axios.defaults.baseURL = 'http://127.0.0.1:8888' //设置全局默认值
axios.defaults.timeout = 5000 //设置5秒超时时间

在组件里直接写接口地址即可:

getData(){
        this.$axios.get('/api/v1/username') //直接写路径就可以了
            .then(response => {this.username=response.data.data})  
            .catch(error =>{
              console.log(error)
            alert(this.error)
            })
      }

Axios 自定义实例默认值

  有时候服务端接口有多个地址,就会涉及请求的域名不同、配置不同等,这时自定义实例可以很好解决。
1、创建src/api/test1.js文件
在这里插入图片描述
2、自定义实例

import axios from "axios";
const instance1 = axios.create({
    baseURL: "http://192.168.0.1",
    timeout: 5000
})
export default instance1 //暴露函数

3、全局main.js注册

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import Test from "@/components/Test";
//import axios from "axios"; 原本注册的axios要取消
import axios from "./api/test1";

//createApp(App).use(router).mount("#app");
const app = createApp(App);
app.use(router).use(router).mount('#app');
app.component('Test', Test)
app.config.globalProperties.$test1=axios  //全局注册

4、组件使用

      getData(){
        this.$test1.get('/test/user') //原本的$axios改为新注册的$test1
            .then(response => {this.username=response.data.data})
            .catch(error =>{
              console.log(error)
            alert(this.error)
            })
      }

Axios 拦截器

拦截器可以拦截每一次请求和响应,然后进行相应的处理。
 请求拦截应用场景:
  • 发起请求前添加header
 响应拦截应用场景:
  • 统一处理API响应状态码200或非200的提示消息
  • 统一处理catch异常提示信息
请求/响应拦截示例:

import axios from "axios";
const instanceUrl = axios.create({
    baseURL: "http://127.0.0.1:8888",
    timeout: 5000
})
export default instanceUrl
instanceUrl.interceptors.request.use(config => {
    config.headers['testHeader'] = '123456'
    return config;
},error =>{
    //alert("请求接口失败")
    console.log("1111111")
    return Promise.reject(error)
})
instanceUrl.interceptors.response.use(response =>{
    return response;
}, error =>{
    console.log(error);
    return Promise.reject(error)
})
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐