axios的使用

本文详细介绍了在Vue项目中如何安装和使用Axios。从局部引用到全局配置,包括GET和POST请求的方法,特别是POST请求中使用qs库处理参数,以及发起并发请求的实现。此外,还讲解了如何对Axios进行全局配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装 axios

使用npm:

$ npm i axiso

使用 bower

$ bower instal axios

使用cdn

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

2.vue中引入

2.1 局部引用

假设我们要在hellow.vue中引用

import axios from 'axios';

下面就可以直接使用了

 methods: {
    // 获取地址列表
    getAdressList() {
      axios.get('http://127.0.0.1:4100/adress/getAdressList').then((result) => {
          。。。。。。。
      });
    },
 }

2.2 全局引用

如果我们在多个页面中都会使用axios获取数据,那么我们可以在全局引用,就不用每一个页面都引用了,因为axios并不是单独为vue设计的,React也是可以使用的,所以不能用Vue.use来调用。但如果将 axios 改写为 Vue 的原型属性,就能解决这个问题
我们以vue-cli为例

在main.js中:

import axios from 'axios';
Vue.prototype.$ajax = axios;

在任何一个vue组件中:

 methods: {
    getSeller() {
      this.$ajax.get('/api/seller').then((result) => {
        console.log(result);
      });
    }
  },

3.get请求

3.1 方法一

发起一个user请求,参数为给定的ID

axios.get('/user?ID=1234')
.then(function(respone){
    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)
   });

4.post请求

API:

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
}).then(function(response){
});

实例:

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

但是有时候会报错

4.1 使用qs封装post请求的参数

axios在发送数据时需要字符串的方式进行发送,
这时就需要qs插件 https://www.npmjs.com/package/qs

npm install qs

可以全局设置,main.js

import Qs from 'qs';
Vue.prototype.$Qs = Qs;

也可以单独的页面设置

import Qs from 'qs';

使用:
(将this.$qs和 Qs进行替换就好了)

changDefaultAdress(address) {
      axios.post('http://127.0.0.1:4100/adress/changDefaultAdress', Qs.stringify({
        addressId: address.addressId
      })).then((result) => {
        console.log(result);
      });
}

5.发起一个多重并发请求

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

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

axios.all([getUerAccount(),getUserPermissions()])
    .then(axios.spread(function(acc,pers){
        //两个请求现在都完成
    }));

6.对axios进行全局的配置

这里写图片描述
ajax.js :

'use strict';

import axios from 'axios';
import qs from 'qs';

//添加一个请求拦截器
axios.interceptors.request.use(config => { // 这里的config包含每次请求的内容
  //在请求发送之前做一些事
  // 判断localStorage中是否存在token
  if (localStorage.getItem('token')) {
    //  存在将api_token写入 request header
    config.headers.apiToken = `${localStorage.getItem('api_token')}`;
  }
  return config;
}, err => {
  return Promise.reject(err);
});

//添加一个返回拦截器
axios.interceptors.response.use(response => {
    //对返回的数据进行一些处理
   // token 已过期,重定向到登录页面  
    if (response.data.code == 4){  
        localStorage.clear()  
        router.replace({  
           path: '/signin',  
           query: {redirect: router.currentRoute.fullPath}  
        })  
    }  
  return response;
}, error => {
  return Promise.resolve(error.response);
});

function checkStatus(response) {
  // 如果http状态码正常,则直接返回数据
  if (response && (response.status === 200 || response.status === 304 ||
    response.status === 400)) {
    return response;
  }
  // 异常状态下,把错误信息返回去
  return {
    status: -404,
    msg: '网络异常'
  };
}

function checkCode(res) {
  // 如果code异常(这里已经包括网络错误,服务器错误,后端抛出的错误),可以弹出一个错误提示,告诉用户
  if (res.status === -404) {
    alert(res.msg);
  }
  if (res.data && (!res.data.success)) {
    // alert(res.data.error_msg)
  }
  return res;
}
// 请求方式的配置
export default {
  post(url, data) { // post
    return axios({
      method: 'post',
      baseURL: '/api',
      url,
      data: qs.stringify(data),
      timeout: 5000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response);
      }
    ).then(
      (res) => {
        return checkCode(res);
      }
    );
  },
  get(url, params) { // get
    return axios({
      method: 'get',
      baseURL: '/api',
      url,
      params, // get 请求时带的参数
      timeout: 5000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(
      (response) => {
        return checkStatus(response);
      }
    ).then(
      (res) => {
        return checkCode(res);
      }
    );
  }
};

main.js中做全局引用

import axios from './utils/ajax.js';
Vue.prototype.$ajax = axios;

组件就可以直接引用了,也不用再再全局引用qs了,因为ajax.js已经引用了

 methods: {
    getSeller() {
      this.$ajax.get('/api/seller').then((result) => {
        console.log(result);
      });
    }
  },

官网:
https://www.npmjs.com/package/axios

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值