Axios的使用(均已实现)

本文详细介绍了如何使用Axios库进行HTTP请求,包括GET和POST方法,参数传递,处理并发请求,创建实例,使用拦截器进行请求和响应的拦截,以及错误处理和取消请求的方法。此外,还展示了在Vue中使用Axios的例子。
摘要由CSDN通过智能技术生成

安装

  • $ npm install axios
    

创建一个axios请求

  • get
    // GET request for remote image
    axios({
      method:'get',
      url:'http://bit.ly/2mTM3nY',
      responseType:'stream'
    })
      .then(function (response) {
        response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
      });
    
    • 传参
      // 直接在 URL 上添加参数 ID=12345
      axios.get('/user?ID=12345')
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
       
      // 也可以通过 params 设置参数:
      axios.get('/user', {
          params: {
            ID: 12345
          }
        })
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
      
  • post
    // Send a POST request
    axios({
      method: 'post',
      url: '/user/12345',
      data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
      }
    });
    
    • 传参
      axios.post('/user', {
          firstName: 'Fred',        // 参数 firstName
          lastName: 'Flintstone'    // 参数 lastName
        })
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
      

执行多个并发请求

  • 处理并发请求的助手函数:

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

  • 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) {
        // 两个请求现在都执行完成
      }));
    // vue中
    this.$http.all([this.axios1(), this.axios2()])
        .then(this.$http.spread(function (res1, res2) {
            console.log('请求1', res1)
            console.log('请求2', res2)
            })).catch((err) => {
             //捕获错误
            })
       axios1() {
          return axios.get('api/test1?ID="1234"&password="12345"')
        },
        axios2() {
          return axios.post('api/test2',qs.stringify({ID: '12345',
          password: '12345'}))
          // axios.get('api/test1?ID="1234"&password="12345"')
          // axios.post('api/test2',qs.stringify({ID: '12345',
        }
    

API

axios(url[, config])

// Send a GET request (default method)
axios('/user/12345');

请求方法的别名

For convenience aliases have been provided for all supported request methods.

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.create([config])

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
// vue中创建实例
const instance = this.$http({
        url: 'api/test1',
        methods: 'get',
        params: {
          ID: '12345',
          password: '123455'
        }
      }).then(
        result => {
          console.log(result.data);
        }
      )

实例方法

      
      
      const instance = axios.create({
        url: '/user',
        
        methods: 'get', //default
        
        // 基础是url 添加到url前面
        baseURL: 'https://some-domain.com/api/',
        
        // transformRequest` 允许在向服务器发送前,修改请求数据
        transformRequest: [function (data, headers) {
          return data
        }],
        
        //  `transformResponse` 在传递给 then/catch 前,允许修改响应数据
        transformResponse: [function (data) {
          return data
        }],
        
        // `headers` 是即将被发送的自定义请求头
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        
        // `params` 是即将与请求一起发送的 URL 参数
        params: {
          ID: 1234
        },
        
        // `paramsSerializer` 是一个负责 `params` 序列化的函数
        paramsSerializer: function (params) {
          return Qs.stringify(params, {arrayFormat: 'brackets'})
        },
        
        data: {
          firstName: 'Fred'
        },
        
        // 设置请求超时的时间
        timeout: 1000, //default 0
        
        // 是否允许跨域
        withCredentials: false, // default
        
        //`adapter` 允许自定义处理请求,以使测试更轻松
        // 返回一个Promise,提供一个有效的回应
        adapter: function (config) {
          /* ... */
        },
        
        // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
        auth: {
          username: 'janedoe',
          password: 's00pers3cret'
        },
        
        responseType: 'json', // default
        
        // 解码方式
        responseEncoding: 'utf8', // default
        
        // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
        xsrfCookieName: 'XSRF-TOKEN', // default
        
        // `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
        xsrfHeaderName: 'X-XSRF-TOKEN', // default
        
        //  `onUploadProgress` 允许为上传处理进度事件展
        onUploadProgress: function (progressEvent) {
          // Do whatever you want with the native progress event
        },
        
        //  `onDownloadProgress` 允许为下载处理进度事件
        onDownloadProgress: function (progressEvent) {
          // Do whatever you want with the native progress event
        },
        
        // 响应体内容的最大长度
        maxContentLength: 2000,
        
        // 定义是否解决或拒绝Promise 对于一个给定的HTTP响应状态码
        //validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。
        //如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 
        //将被 resolve; 否则,promise 将被 rejecte
        // return true 使用Promise的resolve false 使用reject
        validateStatus: function (status) {
          return status >= 200 && status < 300; // default 
        },
        
        // 重定向是最大数量
        maxRedirects: 5, // default
        
        // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。
        // 允许像这样配置选项:。
        // 只有“socketPath”或“Proxy”可以指定。
        // 如果两个指定,使用“socketPath”
        socketPath: null, // default
        
        // 定义一个自定义代理用于执行http和https请求时,分别在node . js
        httpAgent: new http.Agent({ keepAlive: true }),
        httpsAgent: new https.Agent({ keepAlive: true }),
        
        // Proxy对象
        // "proxy" 定义代理服务器的主机名称和端口
        // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
        // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
        proxy: {
          host: '127.0.0.1',
          port: 9000,
          auth: {
            username: 'mikeymike',
            password: 'rapunz3l'
          }
        },
        
        // 指定一个取消标记,可用于取消请求
        cancelToken: new CancelToken(function (cancel) {
        })
      })

响应模式

发送
{
  // `data` 由服务器提供的响应
  data: {},

  // `status`  HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: "OK",

  // `headers` 服务器响应的头
  headers: {},

  // `config` 是为请求提供的配置信息
  config: {}
}
发送后的响应模式
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);
  });

全局响应设置Global axios defaults

  • 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’;

拦截器Interceptors

  • 添加拦截器

    // 添加请求拦截器
    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);
      });
    

    具体实现:

    • 1.新建一个js文件,在这个文件内设置拦截器对象并设置拦截的具体操作然后暴露出来

      // http request 拦截器
      import axios from 'axios'
      let instance = axios.create({
        headers: {
          'content-type': 'application/x-www-form-urlencoded'
        }
      })
      instance.interceptors.request.use(
        config => {
          // 显示请求对象
          console.log("request",config);
          // 显示传递的get参数
          console.log("id",config.params.ID);
          // 修改数据 或者修改其他的配置
          config.params.ID = 1;
          return config
        },
        err => {
          return Promise.reject(err)
        })
      
      // http response 拦截器
      instance.interceptors.response.use(
        response => {
          //拦截响应,做统一处理 
          // 显示响应对象
          console.log("response",response);
          // 修改响应返回的数据
          response.data = 'changed'
          console.log("response.data",response.data);
          return response
        },
        //接口错误状态处理,也就是说无响应时的处理
        error => {
          return Promise.reject(error.response.status) // 返回接口返回的错误信息
        })
        export default instance
      
    • 2.在需要用该拦截器的组件引入该文件

      请添加图片描述

    • 3.直接用暴露的拦截器对象来发请求 替代axios

      请添加图片描述

  • 除去拦截器

    axios.interceptors.request.eject(myInterceptor);
    
  • 可以为自定义 axios 实例添加拦截器。

    var instance = axios.create();
    instance.interceptors.request.use(function () {/*...*/});
    

    错误处理

  • axios.get('/user/12345')
      .catch(function (error) {
        if (error.response) {
          // 请求已发出,但服务器响应的状态码不在 2xx 范围内
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        } else {
          // Something happened in setting up the request that triggered an Error
          console.log('Error', error.message);
        }
        console.log(error.config);
      });
    
  • axios.get('/user/12345', {
      validateStatus: function (status) {
        return status < 500; // Reject only if the status code is greater than or equal to 500
      }
    })
    

取消请求

  • 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
    })
    
    // 取消请求(提示消息是可选的)
    source.cancel('Operation canceled by the user.');
    
  • const CancelToken = axios.CancelToken;
    let cancel;
    //设置cancel来保存取消函数
    axios.get('/user/12345', {
      cancelToken: new CancelToken(function executor(c) {
        // executor 函数接收一个 cancel 函数作为参数
        //把取消函数赋给cancel变量
        cancel = c;
      })
    });
    
    // 取消请求
    cancel();
    
  • 具体实现

请添加图片描述

请添加图片描述

请添加图片描述

      // 取消请求
      const CancelToken = axios.CancelToken;
      const source1 = CancelToken.source();
      const source2 = CancelToken.source();
      // 取消get请求
      axios.get('api/test1', {
        cancelToken: source1.token
      }).then(
        result => {
          console.log(result.data);
        }
      )
      .catch(function (thrown) {
        if (axios.isCancel(thrown)) {
          console.log('Request canceled', thrown.message);
        } else {
          // handle error
        }
      });
      // 取消post请求
      axios.post('api/test2', 
        qs.stringify({
          ID: 1234
        })
      , {
        cancelToken: source2.token
      }).then(
        result => {
          console.log(result.data);
        }
      ).catch(function (thrown) {
        if (axios.isCancel(thrown)) {
          console.log('Response canceled', thrown.message);
        } else {
          // handle error
        }
      });

      // 取消请求 (提示消息是可选的)
      // 这个语句用来取消请求
      source1.cancel('Operation canceled by the user.');
      source2.cancel('Operation canceled by the user.');

浏览器

  • import qs from 'qs';
    const data = { 'bar': 123 };
    const options = {
      method: 'POST',
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      data: qs.stringify(data),
      url,
    };
    axios(options);
    

Node.js

  • const querystring = require('querystring');
    axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
    
  • 或者使用上面的qs
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值