axios 学习笔记

一、什么是axios?

axios是基于PromiseHTTP库,同时支持前端和Node.js

二、特点

1、支持浏览器和node.js
2、支持Promise
3、能拦截请求和响应
4、能转换请求和响应数据
5、能取消请求
6、自动转换JSON数据
7、浏览器端支持防止CSRF(跨站请求伪造)

三、浏览器支持

这里写图片描述

四、安装

npm安装

npm install axios

bower安装

bower install axios

CDN引入

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

五、示例

发起一个GET请求

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);
});

发起一个POST请求

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

同时发起多个请求

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 API

可以通过导入相关配置发起请求

axios(config)

//发起一个post请求

axios({
  method: 'post',
  url: '/user/12345',
  data: {
     firstName: 'xm',
     lastName: 'z'
}
});
//获取远程图片
axios({
    method:'get',
    url:'http://bit.ly/2mTM3nY',
    responseType:'stream'
})
   .then(function (response){
          reponse.data.pipe(fs.createWriteStream('ada_lovelace.jpg')
 } );

七、请求方法别名

为了方便,给所有支持的请求方法提供了别名
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]])

当使用以上别名方法时,urlmethoddata等属性不用在config重复声明。

八、同时发生的请求

以下两个辅助函数用来处理同时发生的多个请求

axios.all(iterable)
axios.spread(callback)

九、创建一个实例

使用通用配置创建一个axios实例

var instance = axios.create({
      baseURL: 'http://127.0.0.1:8011/img/',
      timeout:  1000,
      headers:  {'X-Custom-Header': 'foobar'}
});

十、请求配置

下面所有可用的请求配置项,只有url是必填项,没有设置请求方法的时候,默认是GET方法。

{
  // `url` 是请求的接口地址
  url: '/user',

  // `method` 是请求的方法
  method: 'get', // 默认值

  // 如果url不是绝对路径,那么会将baseURL和url拼接作为请求的接口地址
  // 用来区分不同环境,建议使用
  baseURL: 'https://some-domain.com/api/',

  // 用于请求之前对请求数据进行操作
  // 只用当请求方法为‘PUT’,‘POST’和‘PATCH’时可用
  // 最后一个函数需return出相应数据
  // 可以修改headers
  transformRequest: [function (data, headers) {
    // 可以对data做任何操作

    return data;
  }],

  // 用于对相应数据进行处理
  // 它会通过then或者catch
  transformResponse: [function (data) {
    // 可以对data做任何操作

    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // URL参数
  // 必须是一个纯对象或者 URL参数对象
  params: {
    ID: 12345
  },

  // 是一个可选的函数负责序列化`params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // 请求体数据
  // 只有当请求方法为'PUT', 'POST',和'PATCH'时可用
  // 当没有设置`transformRequest`时,必须是以下几种格式
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },

  // 请求超时时间(毫秒)
  timeout: 1000,

  // 是否携带cookie信息
  withCredentials: false, // default

  // 统一处理request让测试更加容易
  // 返回一个promise并提供一个可用的response
  // 其实我并不知道这个是干嘛的!!!!
  // (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // 响应格式
  // 可选项 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // 默认值是json

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // 处理上传进度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // 处理下载进度事件
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // 设置http响应内容的最大长度
  maxContentLength: 2000,

  // 定义可获得的http响应状态码
  // return true、设置为null或者undefined,promise将resolved,否则将rejected
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  // 最大重定向次数?没用过不清楚
  maxRedirects: 5, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the hostname and port of the proxy server
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  // 代理
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  // 用于取消请求?又是一个不知道怎么用的配置项
  cancelToken: new CancelToken(function (cancel) {
  })
}

十一、响应组成

response由以下信息组成

{
  // 服务端返回的数据
  data: {},

  // 服务端返回的状态码
  status: 200,

  // 服务端返回的状态信息
  statusText: 'OK',

  // 响应头
  // 所有的响应头名称都是小写
  headers: {},

  // axios请求配置
  config: {},

  // 请求
  request: {}
}

十二、拦截器

你可以在thencatch之前拦截请求和响应

// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

如果之后想移除拦截器你可以这么做

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

你也可以为axios实例添加一个拦截器

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

十三、错误处理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 发送请求后,服务端返回的响应码不是 2xx   
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // 发送请求但是没有响应返回
      console.log(error.request);
    } else {
      // 其他错误
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

你可以用validateStatus定义一个http状态码返回的范围.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Reject only if the status code is greater than or equal to 500
  }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值