axios的基础使用

中文文档: http://www.axios-js.com/

npm 仓库地址: https://www.npmjs.com/package/axios

github地址: https://github.com/axios/axios

简介

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

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

安装

  • 1.使用npm安装
$ npm install axios
  • 2.使用bower
$ bower install axios
  • 3.使用CDN

请求示例

  • 1.发送GET请求
// 为给定 ID 的 user 创建请求
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);
  });
  • 2.发送POST请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • 3.执行多个并发请求
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

  • 1.axios(config)
// 发送 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
axios({
    method: 'get',
    url: 'https://cdn.gumt.top/blog_bg.jpg',
    responseType: 'stream'
})
.then(res => {
    res.data.pipe(fs.createWriteStream('blog_bg.jpg'))
})

我们甚至可以利用这个功能去做一些有趣的事情, 比如: 小型的爬虫。

  • 2.axios(url[,config])
// 发送一个GET请求(默认的请求方式)
axios('/usre/123456');

并发请求

// iterable 一个可以迭代的参数如数组等
axios.all(iterable)
//callback要等到所有请求都完成才会执行
axios.spread(callback)

请求方法别名

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这个几个参数不需要再配置中声明。

创建一个axios实例

  • 1.axios.create([config])
let myFetch = axios.create({
    baseURL:"https://some-domain.com/api/",
    timeout:1000,
    headers: {'X-Custom-Header':'foobar'}
})
  • 2.实例方法

注意已定义的配置将和利用create创建的实例的配置合并

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]])

示例:

myFetch.get('getUser/1')
.then(res => {
    console.log(res)
})
// 这里实际发起的是  https://some-domain.com/api/getUser/1  get请求。

请求配置

下面的请求配置项, 只有URL是必须的,如果method 请求方法没有定义,那么它默认是以GET的方式发出的请求。

{
   // `url` 是用于请求的服务器 URL
  url: '/user',


  // `method` 是创建请求时使用的方法
  method: 'get', // default


  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',


  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data, headers) {
    // 对 data 进行任意转换处理
    return data;
  }],


  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],


  // `headers` 是即将被发送的自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},


  // `params` 是即将与请求一起发送的 URL 参数
  // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
  params: {
    ID: 12345
  },


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


  // `data` 是作为请求主体被发送的数据
  // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
  // 在没有设置 `transformRequest` 时,必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属:FormData, File, Blob
  // - Node 专属: Stream
  data: {
    firstName: 'Fred'
  },


  // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
  // 如果请求话费了超过 `timeout` 的时间,请求将被中断
  timeout: 1000,


   // `withCredentials` 表示跨域请求时是否需要使用凭证
  withCredentials: false, // default


  // `adapter` 允许自定义处理请求,以使测试更轻松
  // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
  adapter: function (config) {
    /* ... */
  },


 // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
  // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },


   // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default


  // `responseEncoding` indicates encoding to use for decoding responses
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default


   // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
  xsrfCookieName: 'XSRF-TOKEN', // default


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


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


  // `onDownloadProgress` 允许为下载处理进度事件
  onDownloadProgress: function (progressEvent) {
    // 对原生进度事件的处理
  },


   // `maxContentLength` 定义允许的响应内容的最大尺寸
  maxContentLength: 2000,


  // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },


  // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
  // 如果设置为0,将不会 follow 任何重定向
  maxRedirects: 5, // default


  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default


  // `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
  // (查看后面的 Cancellation 这节了解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}

响应体结构

{
  data:{},
  status:200,
  //从服务器返回的http状态文本
  statusText:'OK',
  //响应头信息
  headers: {},
  //`config`是在请求的时候的一些配置信息
  config: {}
}

可以通过then链式操作获取响应信息

axios.get('/user/12345')
  .then(function(res){
    console.log(res.data);
    console.log(res.status);
    console.log(res.statusText);
    console.log(res.headers);
    console.log(res.config);
  })

配置默认值

可以指定将被用在各个请求的配置默认值

全局的axios默认值

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

自定义实例默认值

// 当创建实例的时候配置默认配置
const instance = axios.create({
  baseURL: 'https://api.example.com'
});
// 当实例创建时候修改配置
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置优先级

config配置将会以优先级别来合并,顺序是lib/defaults.js中的默认配置,然后是实例中的默认配置,最后是请求中的config参数配置,越往后等级越高,后面的会覆盖前面的例子。

//创建一个实例的时候会使用libray目录中的默认配置
//在这里timeout配置的值为0,来自于libray的默认值
var instance = axios.create();
//回覆盖掉library的默认值
//现在所有的请求都要等2.5S之后才会发出
instance.defaults.timeout = 2500;
//这里的timeout回覆盖之前的2.5S变成5s
instance.get('/longRequest',{
  timeout: 5000
});

拦截器

在请求或响应被then或catch处理前拦截他们。

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });


// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

如果你想要移除拦截器,可以进行如下操作。

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

给自定义的axios实例添加拦截器

var myFetch = axios.create();
myFetch.interceptors.request.use(function(){}) // 请求拦截器
myFetch.interceptors.response.use(function(){}) // 响应处理

示例:

let myFetch = axios({
    baseURL: "http://192.168.0.100:8080/api/",
    timeout: 5000
})
myFetch.interceptors.request.use(config => {
    let token = localStorage.getItem("token");
    if (token) {
        config.headers.Authorization = 'Bearer ' + token;
    }
    return config;
}, error => {
    return Promise.reject("Request failed"); 
})
/**
如果后端给我的数据格式如下:
{
status: xxx,  // 状态码
msg: '', // 提示信息
data: [], // 响应数据
success: true // 是否成功
}
*/
myFetch..interceptors.response.use(res => {
    let {msg, status} = res.data;
    console.lg(msg);
    return res.data;
}, error => {
    return Promise.reject("Error, The error could be a network exception or a system exception");
})

错误处理

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.header);
    }else {
      //一些错误是在设置请求的时候触发
      console.log('Error',error.message);
    }
    console.log(error.config);
  });

取消请求

你可以通过一个cancel token来取消一个请求

你可以通过CancelToken.source工厂函数来创建一个cancel token

var CancelToken = axios.CancelToken;
var source = CancelToken.source();


axios.get('/user/12345',{
  cancelToken: source.token
}).catch(function(thrown){
  if(axios.isCancel(thrown)){
    console.log('Request canceled',thrown.message);
  }else {
    //handle error
  }
});


//取消请求(信息的参数可以设置的)
source.cance("操作被用户取消");

你也可以给cancelToken构造函数传递一个executor function来创建一个cancel token:

var cancelToken = axios.CancelToken;
var cance;
axios.get('/user/12345',{
  cancelToken: new CancelToken(function(c){
    //这个executor函数接受一个cancel function作为参数
    cancel = c;
  })
})
//取消请求
cancel();

你可能感兴趣的:(axios的基础使用)