❤ axios的认识和使用

154 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 4 天,点击查看活动详情

❤ axios的认识和使用

1. 认识

官网地址

axios官网地址:www.axios-js.com/

axios中文文档:www.axios-js.com/zh-cn/docs/

在线的CND地址

 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

简介

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

2. axios特点

  • 支持promise:使用Promise管理异步,告别传统callback方式;

  • 支持node端和浏览器端:同样的API,node和浏览器全支持,平台切换无压力;

  • 丰富的配置项:支持拦截器等高级配置;

  • 从浏览器中创建XMLHttpRequests

3. 简单安装使用

1、安装依赖

npm install axios

2、在需要的页面导入

import axios from 'axios'

3、使用

axios.get('地址').then(res=>{
     console.log(res,'axios请求返回')
});

4. 单页面使用

import axios from 'axios'


// 获取用户
function getUserList() {

let api = "http://localhost:8888/api/user";
// console.log(queryParams.value,'queryParams.value'); //查询条件
const params = {
    name: queryParams.value.name,
    age: queryParams.value.age,
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
};

axios({
        method: 'get',
        url: api,
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem("login"),
            'Content-Type': 'application/json;charset=utf-8',
            'Custom-Header': 'custom-value'
        },
        params: params,
    })
    .then(res => {
        console.log(res.data);
        if (res.status == 200) {
            // console.log(res, 'res');
            tableData.value = res.data.data;
            totalvalue.value = res.data.total;
        }
    })
    .catch(error => {
        console.error(error);
    });
}

5. axios的封装和详细使用

(1)执行get请求:

// 为给定 ID 的 user 创建请求

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 
// 上面的请求也可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  

(2)执行post请求:


axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  

(3)执行多个并发请求:

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) {
    // 两个请求现在都执行完成
  }));
  

上述案例来自axios中文文档:www.axios-js.com/zh-cn/docs/

6. 用promise封装axios

在实际项目里为了更方便使用axios获取后台数据,在这里进行封装。ue项目里封装方法一般放在utils文件夹里,src下新建一个utils文件夹,index.js文件。


/* eslint-disable no-unused-vars */
import axios from 'axios';
 
 
// const get = () => {
//     console.log('get请求');
// }
 
// const post = () => {
//     console.log('post请求')
// }
 
// export{
//     get,
//     post
// }
 
// process.env.NODE_ENV环境
let baseURL;
if(process.env.NODE_ENV=='development'){
    baseURL = 'http://132.232.94.151:3000/api'
}else{
    baseURL = '/xxx'
}
// baseURL es6 方法
 
 
const $http = axios.create({
    baseURL,
})
// create 是axios自带的方法
 
export const get = (url,params)=>{
    params = params || {};
    return new Promise((resolve,reject)=>{
        // axiso 自带 get 和 post 方法
        $http.get(url,{
            params,
        }).then(res=>{
            if(res.data.status===0){
                resolve(res.data);
            }else{
                alert(res.data.msg)
            }
        }).catch(error=>{
            alert('网络异常');
        })
    })
}
 
export const post = (url,params)=>{
    params = params || {};
    return new Promise((resolve,reject)=>{
        $http.post(url,params).then(res=>{
            if(res.data.status===0){
                resolve(res.data);
            }else{
                alert(res.data.msg);
            }
        }).catch(error=>{
            alert('网络异常');
        })
    })
}
main.js文件中做如下配置:

import { get, post } from "./utils/index";
Vue.prototype.$http = {
  get,
  post
};

(1)上述使用了构造函数的原型prototype(vue属于构造函数); (2)声明一个全局变量并且把封装好的get和post方法放在里面。

使用封装后的函数:

created() {
    this.getFilmList();
  },
  methods: {
    async getFilmList() {
      const url = "/film/getList";
      // 要访问第二页的话在网址后面加 ?type=2&pageNum=页数
      const res = await this.$http.get(url);
      this.filmList = res.films;
  },
    

注意:因为是promise封装的函数方法,所以使用的时候要加上async 函数(){ await 数据} 不然会报错,因为没有完成异步转同步。