• vue之axios


    什么是 axios?

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

    特性

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

    安装

    npm install axios

    使用

    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);
      });

    POST请求

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

    并发

    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

    // 发送 POST 请求
    axios({
      method: 'post',
      url: '/user/12345',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });
    // 获取远端图片
    axios({
      method:'get',
      url:'http://bit.ly/2mTM3nY',
      responseType:'stream'
    })
      .then(function(response) {
      response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
    });
    // 发送 GET 请求(默认的方法)
    axios('/user/12345');

    创建实例

    const instance = axios.create({
      baseURL: 'https://some-domain.com/api/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'foobar'}
    });
    import axios from 'axios'
    import { getToken } from '@/utils/auth'
    
    // axios.defaults.headers.common['Authorization'] = getToken();  //设置headers
    // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    
    
    // 创建axios实例
    const service = axios.create({
      baseURL: 'http://127.0.0.1:8000', // api的base_url
      timeout: 15000, // 请求超时时间
      // headers: {  // 设置headers
      //   // 'X-Custom-Header': 'foobar',
      //   'Authorization': getToken(),
      //   'Content-Type': 'application/x-www-from-urlencoded'
      // }
    })
    
    // request拦截器
    service.interceptors.request.use(config => {
      if (store.getters.token) {
    
        config.headers= {
          'Authorization': getToken(),
          'Content-Type': 'application/x-www-from-urlencoded'  // 跨域设置headers
        }
        // config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        // config.headers['Authorization'] = AUTH_TOKEN, // 让每个请求携带自定义token 请根据实际情况自行修改
        // config.headers['Content-Type'] = 'application/x-www-from-urlencoded'
      }
      return config
    }, error => {
      // Do something with request error
      console.log(error) // for debug
      Promise.reject(error)
    })
    
    // respone拦截器
    service.interceptors.response.use(
      response => {
      /**
      * code为非200是抛错 可结合自己业务进行修改
      */
        const res = response.data
    
        if (res.code !== 200) {
          Message({
            message: res.message,
            type: 'error',
            duration: 3 * 1000
          })
    
          // 401:未登录;
          if (res.code === 401) {
            MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              store.dispatch('FedLogOut').then(() => {
                location.reload()// 为了重新实例化vue-router对象 避免bug
              })
            })
          }
          return Promise.reject('error')
        } else {
          console.log(response.data,"return")
          return response.data
        }
      },
      error => {
        console.log('err' + error)// for debug
        Message({
          message: error.message,
          type: 'error',
          duration: 3 * 1000
        })
        return Promise.reject(error)
        // return response.data
      }
    )
    
    export default service

    全局的 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';

    自定义实例默认值

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

    配置的优先顺序

    配置会以一个优先顺序进行合并。这个顺序是:在 lib/defaults.js 找到的库的默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后者将优先于前者。这里是一个例子:

    // 使用由库提供的配置的默认值来创建实例
    // 此时超时配置的默认值是 `0`
    var instance = axios.create();
    
    // 覆写库的超时默认值
    // 现在,在超时前,所有请求都会等待 2.5 秒
    instance.defaults.timeout = 2500;
    
    // 为已知需要花费很长时间的请求覆写超时设置
    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);
      });

    如果你想在稍后移除拦截器,可以这样:

    const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
    axios.interceptors.request.eject(myInterceptor);
    可以为自定义 axios 实例添加拦截器
    const instance = axios.create();
    instance.interceptors.request.use(function () {/*...*/});

    错误处理

    axios.get('/user/12345')
      .catch(function (error) {
        if (error.response) {
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        } else if (error.request) {
          // The request was made but no response was received
          // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
          // http.ClientRequest in node.js
          console.log(error.request);
        } else {
          // Something happened in setting up the request that triggered an Error
          console.log('Error', error.message);
        }
        console.log(error.config);
      });

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

    axios.get('/user/12345', {
      validateStatus: function (status) {
        return status < 500; // Reject only if the status code is greater than or equal to 500
      }
    })

    使用 application/x-www-form-urlencoded format

    默认情况下,axios将JavaScript对象序列化为JSON。 要以application / x-www-form-urlencoded格式发送数据,您可以使用以下选项之一。

    在浏览器中,您可以使用URLSearchParams API,如下所示:

    onst params = new URLSearchParams();
    params.append('param1', 'value1');
    params.append('param2', 'value2');
    axios.post('/foo', params);

    使用qs库编码数据:

    const qs = require('qs');
    axios.post('/foo', qs.stringify({ 'bar': 123 }));

    本文来自axios中文文档|axios中文网

  • 相关阅读:
    工具链中 Binutils的内容
    Qt 4.5 新功能逐一看 – 性能优化
    qt 打不开 用于触摸屏校准的文件
    Unicode 编码范围
    Android OpenGL ES 分析与实践
    Armlinux GCC 交叉编译工具
    二维矢量图形算法加速标准 OpenVG
    电路和程序一样,不是设计出来的,是调出来的
    电子元件又一话电容篇
    TVS管
  • 原文地址:https://www.cnblogs.com/aaronthon/p/13144069.html
Copyright © 2020-2023  润新知