axios的使用

1.npm安装:npm install axios

2.axios发送请求后返回的是一个promise

3.axios发送get请求:

import axios from 'axios';

axios.get('http://localhost:8080/getData?username=abc&id=1').then(res=>{

  console.log(res);

});

参数传递另一种写法:

import axios from 'axios';

axios.get('http://localhost:8080/getData',{params:{id:1,username:'abc'}}).then(res=>{

  console.log(res);

});

4.axios发送post请求:

import axios from 'axios';

axios.post('http://localhost:8080/postData',"name=张三&urs=test").then(res=>{

  console.log(res);

});

5.axios发送并发请求,使用asios.all(),它的功能类似于promise.all():

import axios from 'axios';

axios.all([

  axios.get('http://localhost:8080/getData'),

  axios.get('http://localhost:8080/getData1')

]).then(res=>{

  console.log(res);//这里的res是一个数组,分别是每个请求的返回数据

}).catch(err=>{

  console.log(err);

});

6.axios的全局配置,可以配置axios请求的baseurl,超时时间,请求头,返回数据格式等

axios.default.baseURL="http://localhost:8080";

axios,default.timeout = 5000;

axios.default.headers.post['content-type']='application/x-www-form-urlencoded';

axios.defaults.transformRequest=function(data){//返回值转化为字符串形式

 data= JSON.stringify(data);

  return data; 

};

7.axios的实例配置,由于在同一个项目中我们可能不只是只请求一个域名的接口,所有axios的全局配置不能解决这个问题,就需要实例配置。

let local = axios.create({

  baseURL :"http://localhost:8080",

  timeout:5000

});

local.get('getData').then(res=>{

  console.log(res);

});

8.axios的拦截器。拦截器就是在请求发送出去之前统一拦截进行一些处理,在决定放行或者拦截。同样在服务器返回数据的时候也可以进行拦截进行处理。

比如给请求带上token,或者判断token是否过期等。或者对服务器返回的数据进行处理等。

let local = axios.create({

  baseURL :"http://localhost:8080",

  timeout:5000

});

//请求拦截器

local.interceptors.request.use(//对local 实例做一个请求拦截,方法中第一个参数是拦截的一些配置,第二个参数是拦截错误后的处理。

  config=>{

    console.log("拦截成功,进行处理。");

    return config;//放行

  },err=>{

    console.log(err);

  }

);

//响应拦截器

local.interceptors.response.use(//对local 实例做一个响应拦截,方法中第一个参数是拦截的一些配置,第二个参数是拦截错误后的处理。

  config=>{

    console.log("接受到服务器返回的数据,进行处理。");

    return config;//放行

  },err=>{

    console.log(err);

  }

);

9.封装axios

如:新建request.js:

import axios from 'axios';

const instance = asiox.create({

  baseURL:'http://api.network.cn/admin',

  timeout:5000

});

//todo:这里还可以给instance添加一些拦截器的设置,比如统一添加token等

export function get(url,params){

  return instance.get(url,{params});

}

export function post(url,params){

  return instance.post(url,{params});

}

使用封装的axios:

import{get,post} './request.js'

let link={

  name:'百度',

  url:'www.baidu.com'

};

post('/url/add',link).then(res=>{

  console.log(res);

}).catch(err=>{

  conso.log(err);

});

get('/url')..then(res=>{

  console.log(res);

}).catch(err=>{

  conso.log(err);

});

原文地址:https://www.cnblogs.com/maycpou/p/14673038.html