axios用法

axios是什么

基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中

axios的特点

  1. 从浏览器中创建 XMLHttpRequests
  2. 从 node.js 创建 http 请求
  3. 支持 Promise API支持 Promise API
  4. 拦截请求和响应 (就是有interceptor,拦截器)
  5. 转换请求数据和响应数据
  6. 取消请求
  7. 自动转换 JSON 数据
  8. 客户端支持防御 XSRF
//执行get请求
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
 console.log(response);
}).catch(function (error) {
 console.log(error);
});

// Optionally the request above could also be done as
axios.get('/user', {
 params: {
   ID: 12345
 }
}).then(function (response) {
 console.log(response);
}).catch(function (error) {
 console.log(error);
});
//首先创建一个Axios实例
var axiosIns = axios.create({
    baseURL: '请求地址',
    timeout: 延时时长,
    headers: {'X-product': 'h5'}
})
//设置request拦截器
axiosIns.interceptors.request.use(request=>{
    //处理request,可以对所有请求统一处理请求头等
})
//response拦截器
axiosIns.interceptors.response.use(response=>{
    //处理response,可以对所有响应做处理
})

//实例方法
axios#request(config)
axios#get(url[,config])
axios#delete(url[,config])
axios#head(url[,config])
axios#post(url[,data[,config]])
axios#put(url[,data[,config]])
axios#patch(url[,data[,config]])

//请求配置
{
  baseURL: 'https://www.tomandjerry.club/api/',
    url: '/user',
    method: 'get',
    //transformRequest 允许在向服务器发送前,修改请求数据,
    //只能用在PUT POST PATCH 这几个请求方法中,
    //后面的数组中的函数必须返回一个字符串,或ArrayBuffer,或Stream
    transformRequst: [function(data){
        //对data进行任意转换处理
        return data;
    }],
    //transformResponse 在传递给then/catch 前,允许修改响应数据
    transformResponse: [function(data){
        //对data进行任意转换处理
    }],
    //自定义请求头
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    //params 必须是一个 无格式对象 或 URLSearchParams对象
    params: {
        ID: 1234
    },
    //paramsSerializer 是负责params序列化的函数
    //什么是序列化和反序列化,见下
    paramsSerializer: function(params){
        return Qs.strinfify(params,{arrayFormat: 'brackets'})
    },
    //data 主体的发送数据
    //只适用于PUT POST 和PATCH
    //在没有设置transformRequest时,必须是以下类型之一
    //string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
    //浏览器专属:FomData,File,Blob
    //Node专属:Stream
    data: {
        firstName: 'Jack'
    },
    //timeout 请求超时,如果请求超过了timeout指定的时间则请求将被中断
    timeout: 1000,
    //表示跨域请求时是否需要使用凭证
    withCredentials: false,//默认的
    //adapter 允许自定义处理请求,使测试更轻松
    //返回 一个promise并应用一个有效的响应
    adapter: function(config){
        
    },
    //auth 表示应该使用HTTP基础验证,并提供凭据
    //将设置一个Authorization头,覆写掉现有的任意使用headers设置的自定义Authorization头
    auth: {
        username: 'janedoe',
        password: 'ssss'
    },
    //responseType 表示服务器响应的数据类型,
    //可以是arraybuffer blob document json text stream
    responseType: 'json',//默认
    //xsrfCookieName 是用作xsrf token 的值的cookie的名称
    xsrfCookieName: 'XSRF-TOKEN',//默认
    //xsrfHeaderName 是承载xsrf token 的值的HTTP头的名称
    xsrfHeaderName: 'X-XSRF-TOKEN', // 默认
    //onUploadProgress 允许为上传处理进度事件
    onUploadProgress: function(progressEvent){
        // 对原生进度事件的处理
    },
    //onDownloadProgress 允许为下载处理进度事件
    onDownloadProgress: function(progressEvent){
        //对原生进度事件的处理
    },
    //maxContentLength 定义允许的响应内容的最大尺寸
    maxContentLength: 2000,
    //validateStatus 定义对于给定的HTTP 响应状态码是 resolve 或 reject  
    //如果validateStatus返回true(或者设置为 `null` 或 `undefined`),
    //promise 将被 resolve; 否则,promise 将被 rejecte
    validateStatus: function (status) {
        return status >= 200 && status < 300; // 默认
     },
     //maxRedirects 定义在 node.js 中 follow 的最大重定向数目
     // 如果设置为0,将不会 follow 任何重定向
     maxRedirects: 5, // 默认的
     //httpAgent和httpsAgent分别在node.js中用于定义在执行http和https 时使用的自定义代理。
     //允许像这样配置选项:keepAlive默认没有启用
     httpAgent: new http.Agent({ keepAlive: true }),
     httpsAgent: new https.Agent({ keepAlive: true }),
     //proxy定义代理服务器的主机名称和端口,auth表示HTTP基础验证应当用于连接代理,并提供凭据
     //这将会设置一个Proxy-Authorization头,
     //覆写掉已有的通过使用header设置的自定义Proxy-Authorization头。
     proxy: {
        host: '127.0.0.1',
        port: 9000,
        auth: : {
          username: 'mikeymike',
          password: 'rapunz3l'
        }
      },
      //cancelToken 指定用于取消请求的 cancel token
     cancelToken: new CancelToken(function (cancel) {
     
      })
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值