Axios的基本使用

什么是Axios

Axios是一个基于promise的HTTP库,可以用在浏览器和node.js中。

Axios的特性

1. 从浏览器中创建XMLHttpRequests
2. 从node.js创建http请求
3. 支持 Promise API
4. 拦截请求和响应
5. 取消请求
6. 自动转换JSON数据
7. 客户端支持防御XSRF

使用方式

1. npm

npm install axios

2. cdn

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

Axios的基本使用

案例使用的请求链接来自于提供免费API服务的网站。

JSONPlaceholderDummy sample rest api

案例全局请求前缀

var base_url= 'https://jsonplaceholder.typicode.com',
    employee_create_url = 'http://dummy.restapiexample.com/api/v1/create',
    emploee_get_url = 'http://dummy.restapiexample.com/api/v1/employees';

1. Get请求

axios({
  method: 'get',
  url: `${base_url}/todos`,
  params: {
    _limit: 5
  }
})
  .then(function (res) {
    console.log(res.data);
  })
  .catch(function (err) {
    console.log(err);
  });
axios({
  method: 'get',
  url: `${base_url}/todos?_limit=5`
})
  .then(function (res) {
    console.log(res.data);
  })
  .catch(function (err) {
    console.log(err);
  });
axios.get(`${base_url}/todos?_limit=5`)
  .then(function (res) {
    console.log(res.data);
  })
  .catch(function (err) {
    console.log(err);
  });

2. Post请求

axios({
  method: 'post',
  url: `${base_url}/todos`,
  data: {
    title: 'yueluo',
    completed: false
  }
})
  .then(function (res) {
    console.log(res.data);
  })
  .catch(function (err) {
    console.log(err);
  });
axios.post(`${base_url}/todos`, {
  title: 'yueluo',
  completed: false
})
  .then(function (res) {
    console.log(res.data);
  })
  .catch(function (err) {
    console.log(err);
  });

3. PUT/PATCH请求

Put通常用于替换某条数据
Patch通常用于更新某条数据的部分信息

axios.put( `${base_url}/todos/1`, {
  title: 'yueluo',
  completed: true
})
  .then(function (res) {
    console.log(res.data);
  })
  .catch(function (err) {
    console.log(err);
});
axios.patch(`${base_url}/todos/1`, {
  title: 'yueluo',
  completed: true
})
  .then(function (res) {
    console.log(res.data);
  })
  .catch(function (err) {
    console.log(err);
  });

4. Delete请求

axios.delete(`${base_url}/todos/1`)
  .then(function (res) {
    console.log(res);
  })
  .catch(function (err) {
    console.log(err);
  });

5. 批量发送请求

axios.all([
  axios.get(`${base_url}/todos`),
  axios.get(`${base_url}/posts`),
])
  .then(axios.spread((todos, posts) => {
    console.log(todos.data);
    console.log(posts.data);
  }))
  .catch(function (err) {
    console.log(err);
  })

6. 自定义请求头

const config = {
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
  }
}

axios.post('http://dummy.restapiexample.com/api/v1/create', {
  name: 'yueluo',
  salary: 1000,
  age: 10
}, config)
  .then(res => {
    console.log(res.data);
  })
  .catch(err => console.log(err));

7. 转换请求和响应数据

const options = {
  method: 'post',
  url: employee_create_url,
  data: {
    name: 'yueluo',
    salary: 1000,
    age: 10
  },
  transformResponse: axios.defaults.transformResponse.concat(res => {
    const data = res.data;
    data.name = data.name.toUpperCase()
    return res;
  })
};

axios(options)
  .then(res => {
    console.log(res.data);
  })
  .catch(err => console.log(err));

8. 错误信息处理

axios.get(emploee_get_url + 'a', {
  // 可以使用validateStatus拦截错误信息,根据错误状态进行判断
  // validateStatus: function (status) {
  //   return status < 500
  // }
})
  .then(res => {
    console.log(res.data);
  })
  .catch(err => {
    if (err.response) {
      console.log(err.response.data);
      console.log(err.response.status);
      console.log(err.response.headers);

      if (err.response.status === 404) {
        alert('url is not found.');
      } else if (err.request) {
        console.error(err.message);
      }
    }
  });

9. 取消请求

const source = axios.CancelToken.source();

axios.get(emploee_get_url, {
  cancelToken: source.token
})
  .then(res => {
    console.log(res.data);
  })
  .catch(thrown => {
    if (axios.isCancel(thrown)) {
      console.log('Some message:', thrown.message);
    }
  });

if (true) {
  setTimeout(() => {
    source.cancel('Request Canceled.');
  }, 500);
}

10. 请求拦截与响应拦截

可以使用拦截器来做日志收集

axios.interceptors.request.use(config => {
  console.log(`
    ${config.method.toUpperCase()} request send to ${config.url} at ${new Date().getTime()}
  `)
  return config;
}, error => {
  return Promise.reject(error);
});

11. 创建Axios实例、设置请求超时时间

const axiosInstance = axios.create({
  baseURL: 'http://dummy.restapiexample.com/api/v1',
});

axiosInstance.get('/employees', {
  timeout: 3000
})
  .then(res => console.log(res.data))
  .catch(err => console.log(err));

12. Axios全局配置

Token相关的参数可以再Axios全局配置

axios.defaults.headers.common['Authorization'] = 'JzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';