axios

51 阅读1分钟

axios是什么

axios是一个基于promise封装好的发送请求、返回响应的http库,可以应用在浏览器中和node.js中。

axios的特性

  1. 在浏览器中发送请求会创建 XMLHttpRequests
  2. 在node.js 发送请求会创建 http请求
  3. Promise封装,故支持Promise API
  4. 支持拦截器interceptors,可以分别设置请求拦截和响应拦截,在发出请求和响应到达then之前进行判断处理
  5. 转换请求数据和响应数据
  6. 支持取消请求
  7. 自动转换 JSON 数据
  8. 客户端支持防御 XSRF攻击

axios的安装

npm安装:$ npm install axios cdn引用:

axios的使用

常用方法 get. post request

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  }) 
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

axios({
        method: 'POST/PUT/GET',
        url: 'http://localhost:3000/posts',
        // 设置请求体
        data: {
          title: "活着",
          author: "余华"
        }
      }).then(response => {
        console.log(response);
      })

axios request 可以传入很多请求配置

axios.request({ url: '/user', method: 'get', // 默认 baseURL: '/api', //... })