zoukankan      html  css  js  c++  java
  • [Vue]axios的使用

    一、axios 简介

    1.axios特征

    axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

      • 从浏览器中创建 XMLHttpRequest
      • 从 node.js 发出 http 请求
      • 支持 Promise API
      • 拦截请求和响应
      • 转换请求和响应数据
      • 取消请求
      • 自动转换JSON数据
      • 客户端支持防止 CSRF/XSRF

    2.引入方式:

    //使用npm
    $ npm install axios
    //使用bower
    $ bower install axios
    //或者使用cdn:
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    安装其他插件的时候,可以直接在 main.js 中引入并使用 Vue.use()来注册,但是 axios并不是vue插件,所以不能 使用Vue.use(),所以只能在每个需要发送请求的组件中即时引入。

    为了解决这个问题,我们在引入 axios 之后,通过修改原型链,来更方便的使用。

    //main.js

    import axios from 'axios'
    Vue.prototype.$http = axios

    3.使用 $http命令

    在 main.js 中添加了这两行代码之后,就能直接在组件的 methods 中使用 $http命令

    methods: {
      postData () {
        this.$http({
          method: 'post',
          url: '/user',
          data: {
            name: 'xiaoming',
            info: '12'
          }
       })
    }

    二、下面来介绍axios的具体使用:

    1.axios(config)

    // 发送一个 POST 请求
    axios({
      method: 'post',
      url: '/user/12345',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });

    2.axios(url[, config])

    // 发送一个 GET 请求 (GET请求是默认请求模式)
    axios('/user/12345');

    请求方法别名

    为了方便起见,已经为所有支持的请求方法提供了别名。当使用别名方法时,不需要在config中指定url,method和data属性。

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

    2.1执行 GET 请求

    // 向具有指定ID的用户发出请求
    $http.get('/user?ID=12345')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    // 也可以通过 params 对象传递参数
    $http.get('/user', {
        params: {
          ID: 12345
        }
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    2.2执行 POST 请求

    $http.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    3.并发

    帮助函数处理并发请求。

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

    执行多个并发请求

    function getUserAccount() {
      return $http.get('/user/12345');
    }
    function getUserPermissions() {
      return $http.get('/user/12345/permissions');
    }
    axios.all([getUserAccount(), getUserPermissions()])
      .then($http.spread(function (acct, perms) {
        //两个请求现已完成
      }));

    4.创建实例

    您可以使用自定义配置创建axios的新实例。

    axios.create([config])

    var instance = axios.create({
      baseURL: 'https://some-domain.com/api/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'foobar'}
    });

    实例方法

    可用的实例方法如下所示。 指定的配置将与实例配置合并。

    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]])
    axios#getUri([config])

    config详细见:https://www.cnblogs.com/vickylinj/p/10889028.html

    5.响应格式

    请求的相应包含以下信息

    {
      // `data` is the response that was provided by the server
      data: {},
    
      // `status` is the HTTP status code from the server response
      status: 200,
    
      // `statusText` is the HTTP status message from the server response
      statusText: 'OK',
    
      // `headers` the headers that the server responded with
      // All header names are lower cased
      headers: {},
    
      // `config` is the config that was provided to `axios` for the request
      config: {},
    
      // `request` is the request that generated this response
      // It is the last ClientRequest instance in node.js (in redirects)
      // and an XMLHttpRequest instance the browser
      request: {}
    }

    使用 then 时,您将收到如下响应:

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

    6.配置默认值

    6.1全局默认值

     

    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';

     

    6.2自定义实例的默认值

    // Set config defaults when creating the instance
    const instance = axios.create({
      baseURL: 'https://api.example.com'
    });
    
    // Alter defaults after instance has been created
    instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

    6.3配置的优先级

    config中配置的值>实例方法的defaults的配置值>库中defaults的配置值

    // Create an instance using the config defaults provided by the library
    // At this point the timeout config value is `0` as is the default for the library
    //
    const instance = axios.create();
    
    // Override timeout default for the library
    // Now all requests using this instance will wait 2.5 seconds before timing out
    //实例的配置值
    instance.defaults.timeout = 2500;
    
    // Override timeout for this request as it's known to take a long time
    //config的配置值
    instance.get('/longRequest', {
      timeout: 5000
    });

    7.拦截器

    你可以截取请求或响应在被 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);
       });
    //去除拦截器
    const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
    axios.interceptors.request.eject(myInterceptor);

    8.处理错误

    axios.get('/ user / 12345')
       .catchfunction(error){
         if(error.response){
           //请求已发出,但服务器使用状态代码进行响应
           //落在2xx的范围之外
           console.log(error.response.data);
           console.log(error.response.status);
           console.log(error.response.headers);
         } else {
           //在设置触发错误的请求时发生了错误
           console.log('Error',error.message);
         }}
         console.log(error.config);
       });

    您可以使用validateStatus配置选项定义自定义HTTP状态码错误范围。

    axios.get('/ user / 12345',{
       validateStatus:function(status){
         return status < 500; //仅当状态代码大于或等于500时拒绝
       }}
    })

    9.取消请求

    使用cancel token取消请求

    9.1使用CancelToken.source工厂创建一个cancel token

     

    const CancelToken = axios.CancelToken;
    const 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
      }
    });
    
    axios.post('/user/12345', {
      name: 'new name'
    }, {
      cancelToken: source.token
    })
    
    // cancel the request (the message parameter is optional)
    source.cancel('Operation canceled by the user.');

     

    9.2通过传递一个执行函数给CancelToken构造函数来创建一个cancel token:

    const CancelToken = axios.CancelToken;
    let cancel;
    
    axios.get('/user/12345', {
      cancelToken: new CancelToken(function executor(c) {
        // An executor function receives a cancel function as a parameter
        cancel = c;
      })
    });
    
    // cancel the request
    cancel();

    参照官网:http://www.axios-js.com/docs/

     翻译:https://www.cnblogs.com/zhouyangla/p/6753673.html

  • 相关阅读:
    SSM应用(五)--参数绑定
    SSM应用(四)--SpringMVC入门
    Oracle常用函数
    SSM应用(三)--Spring整合MyBatis
    SSM应用(二)--注解的使用
    SSM应用(一)--Spring入门
    MyBatis学习(十四)--逆向工程使用
    MyBatis学习(十三)--缓存
    MyBatis学习(十二)--懒加载
    MySQL常用函数
  • 原文地址:https://www.cnblogs.com/vickylinj/p/10888698.html
Copyright © 2011-2022 走看看