Axios基础使用

  1. //添加一篇新的文章
  2. btns[1].onclick = function(){
  3. //发送AJAX请求
  4. axios({
  5. //请求类型
  6. method:'POST',
  7. //URL
  8. url:'http://localhost:3000/posts',
  9. //设置请求体
  10. data:{
  11. title:'今天天气不错',
  12. author:'张三'
  13. }
  14. }).then(response => {
  15. console.log(response);
  16. });
  17. }

Axios其他使用

  1. //发送 GET 请求
  2. btns[0].onclick = function(){
  3. // axios()
  4. axios.request({
  5. method:'GET',
  6. url:'http://localhost:3000/comments'
  7. }).then(response => {
  8. console.log(response);
  9. });
  10. }
  11. //发送 POST 请求
  12. btns[1].onclick = function(){
  13. // axios()
  14. axios.post(
  15. 'http://localhost:3000/comments',
  16. {
  17. "body":"喜大普奔",
  18. "postId":2
  19. }
  20. ).then(response => {
  21. console.log(response);
  22. })
  23. }

Axios默认配置

  1. //默认配置
  2. axios.defaults.method = 'GET';//设置默认的请求类型为GET
  3. axios.defaults.baseURL = 'http://localhost:3000';//设置基础URL
  4. axios.defaults.params = {id:100};
  5. axios.defaults.timeout = 3000;
  6. btns[0].onclick = function(){
  7. axios({
  8. url:'/posts'
  9. }).then(response => {
  10. console.log(response);
  11. })
  12. }

Axios实际是调了Axios.prototype.request函数

Axios取消请求

  1. const btns = document.querySelectorAll('button');
  2. //2.声明全局变量
  3. let cancel = null;
  4. //发送请求
  5. btns[0].onclick = function(){
  6. //检测上一次的请求是否已经完成
  7. if(cancel !== null){
  8. cancel();
  9. }
  10. axios({
  11. method:'GET',
  12. url:'http://localhost:3000/posts',
  13. //1.添加配置对象的属性
  14. cancelToken: new axios.CancelToken(function(c){
  15. //3. 将 c 的值赋值给 cancel
  16. cancel = c;
  17. })
  18. }).then(response=>{
  19. console.log(response);
  20. //将cancel的值初始化
  21. cancel = null;
  22. })
  23. }
  24. //绑定第二个事件 取消请求
  25. btns[1].onclick = function(){
  26. cancel();
  27. }

Axios取消请求的原理

Axios取消请求最核心的方法是CanelToken。
CancelToken内部维护了一个Promise对象,其默认状态是pending。axios把取消请求的代码放在promise成功的回调中,只要改变promise执行的状态,就可以取消请求。而这个将promise状态改变的函数暴露给了外层,在需要的时候去执行它,promise的状态就改变了。