zoukankan      html  css  js  c++  java
  • axios数据请求封装

    anxious数据请求封装以及拦截器

      1 /* 做数据请求封装 */
      2 import axios from 'axios'
      3 // 1. axios默认配置
      4 // axios.defaults.baseURL = 'http://localhost:3000';
      5 // axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
      6 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
      7 
      8 
      9     // axios.create({
     10     //   timeout: 1000,
     11     // });
     12 
     13 
     14 // 2. 开始封装
     15 
     16     const request = ({
     17       // axios选项
     18       url,
     19       method = 'GET',
     20       headers,
     21       params,
     22       data,
     23       withCredentials = false
     24     }) => {
     25       return new Promise(( resolve,reject ) => {
     26         /* 1. 数据请求处理 */
     27         switch ( method) {
     28           case 'POST':
     29             axios({
     30               url,
     31               method,
     32               data,
     33               headers,
     34               withCredentials
     35             }).then( res => resolve( res ))
     36               .catch( err =>reject( err ))
     37             break;
     38 
     39           default:
     40             /* get put  delete */
     41             axios({
     42               url,
     43               method,
     44               headers,
     45               params,
     46               withCredentials
     47             }).then( res => resolve( res ))
     48               .catch( err => reject( err ))
     49             break;
     50         }
     51 
     52         /* 2. 拦截器 */
     53           // 添加请求拦截器
     54           axios.interceptors.request.use(function (config) {
     55             // 在发送请求之前做些什么
     56             return config
     57           }, function (error) {
     58             // 对请求错误做些什么
     59             return Promise.reject(error);
     60           });
     61 
     62           // 添加响应拦截器
     63           axios.interceptors.response.use(function (response) {
     64             // 对响应数据做点什么
     65             return response;
     66           }, function (error) {
     67             // 对响应错误做点什么
     68             return Promise.reject(error);
     69           });
     70 
     71       })
     72     }
     73 
     74 
     75     export default request
  • 相关阅读:
    Linux shell中运行命令后加上字符“&”的作用(转)
    初探Nginx架构
    NeoLoad系列- 快速上手教程
    Web服务器性能压力测试工具
    Web页面性能测试工具浅析
    主流压力测试工具推荐
    Jmeter系列-webdriver代码范例
    Jmeter系列-webdriver插件
    Jmeter系列-自动生成html报告
    loadrunner如何监控windows系统的资源
  • 原文地址:https://www.cnblogs.com/likecn/p/11791152.html
Copyright © 2011-2022 走看看