Vue 中使用 axios(十一)

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

1、安装 axios:

cnpm install axios --save

2、引入 axios:

import Axios from "axios"
Vue.prototype.$axios = Axios

3、使用示例:

<template>
  <div id="app">
     
  </div>
</template>
<script>
import Learn from "./components/Learn"
// 引入 qs ,这个库是 axios 里面包含的
import Qs from 'qs'

export default {
  name: "App",
  components: {
    Learn   // 注入
  },
  data() {
    return {
      
    }
  },
  mounted() {
    // get 请求
    this.$axios.get("/api/student/get/1")
    .then(res => {
      console.log(res.data)
    })
    .catch(error => {
      console.log(error)
    })

    // get 请求
    this.$axios.get("/api/student/getStudent", {
      params: {
        id: 1
      }
    })
    .then(res => {
      console.log(res.data);
    })
    .catch(error => {
      console.log(error);
    });

    // post 请求,默认的 content-type 为 application/json
    this.$axios.post("/api/student/addStudent", {
      stuId: 20,
      stuName: "Python"
    })
    .then(res => {
        console.log(res.data)
    })
    .catch(error => {
        console.log(error)
    })

    // post 请求,QS 模块会将请求参数的 content-type 转换为 application/x-www-form-urlencoded
    this.$axios.post("/api/student/addStudent", Qs.stringify({
      stuId: 21,
      stuName: 'Linux'
    }))
    .then(res => {
      console.log(res.data)
    })
    .catch(error => {
      console.log(error)
    })

  }
  
};
</script>

4、跨域配置示例(修改 config/index.js):

// 跨域配置
proxyTable: {
  '/api': {
    target: 'http://localhost:8087',  // 接口域名
    changeOrigin: true,  // 是否跨域
    pathRewrite: {
      '^/api': ''   // 需要rewrite重写的
    }
  }

}

通常正式环境跨域配置,由服务器端来设置。

5、执行多个并发请求:

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

6、响应结构:

{
  // `data` 由服务器提供的响应
  data: {},

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',

  // `headers` 服务器响应的头
  headers: {},

  // `config` 是为请求提供的配置信息
  config: {}
}

使用 then 时,将接收下面这样的响应:

axios.get('/user/12345')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

7、全局的 axios 默认值:

// main.js
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

或者:

 // main.js:
 Vue.prototype.HOST = "/api"
 // 访问:
 var url = this.HOST + "/studnet/get/1"

8、拦截器 -- 在请求或响应被 thencatch 处理前拦截它们:

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

9、错误处理:

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 请求已发出,但服务器响应的状态码不在 2xx 范围内
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

 

 

 

参考:

《Vue.js 实战》

https://www.kancloud.cn/yunye/axios/234845

https://cn.vuejs.org/v2/guide/

posted @ 2020-03-25 00:32  d0usr  阅读(329)  评论(0编辑  收藏  举报