2020-03-19(axios)

                                            axios


基于promise用于浏览器和node.js的http客户端

1.特点:

1.支持浏览器和node.js

2.浏览器端支持防止CSRF(跨站请求伪造)

3.支持promise

4.能够拦截请求和响应

5.能够转换请求和响应数据

6.能取消请求

7.它能自动转换为json的数据

2.如何使用

1.安装 npm install --save axios

2.在main.js或者index.js

import axios from "axios"

Vue.prototype.$http=axios

3.基本的api的方法

1.执行get请求,有两种方式

  第一种方式:将参数直接写在url中

axios.get("/getName?id=12").then((res)=>{}).catch((err)=>{})

  第二种方式:将参数写在params中

axios.get("/getName",{params:{id:12}}).then((res)=>{}).catch((err)=>{})

  created(){

    // this.$http 等价于 axios

    this.$http.get("https://xxdfg/uuuuil/klkl?id=14").then((res) => {

      console.log(res)

    });

    this.$http.get("https://xxdfg/uuuuil/klkl",{params:{id:14}}).then((res) => {

      console.log(res)

    })

  }

    2.执行post请求,注意执行post请求的参数的时候,不需要写params字段中,这里要注意和get请求的第二种方式区别开来

axios.post("/getName",{id:123}).then((res)=>{}).catch((err)=>{})

4.通过向axios传递相关的配置来创建请求

    url:请求路径 string类型

    method:请求的方法

    baseURL:baseURL会自动加载url的前面

    headers:自定义请求消息头

    params: 用来传递参数  

    timeout:超时的时间,超过时间,请求就会终止

    基本方式发送post请求

    axios({

        method:"post",

        url:“”

    })

5 配置默认值

    axios.default.baseURL=""

    axios.default.headers.common["sk"]=auto_token;

    axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';

6.执行多个并发

axios.all()和promise.all()的机制是一样的,都是可以执行多个并发,要么全部成功走then,要么就走catch

function getName(){

return  axios.get("/getName")

}

function getAge(){

return  axios.get("/getAge")

}

axios.all([getName(),getAge()]).then((res)=>{}).catch((err)=>{

})

7.拦截器

1.在请求之前拦截请求

//添加请求拦截器

axios.interceptors.request.use(function(config){

//发送请求之前做了什么事情

return config

},function(err){

//对请求的错误做了什么

return Promise.reject(err)

})

2.在响应的时候进行拦截

axios.interceptors.response.use(function(response){

//对响应的数据做什么操作

return response

},function(err){

//对请求的错误做了什么

return Promise.reject(err)

})

8.请求方法别名

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

注释

当使用以上别名方法时,url,method和data等属性不用在config重复声明

  

  

你可能感兴趣的:(2020-03-19(axios))