优美编程前端Vue专辑

axios-日常使用篇

2020-02-18  本文已影响0人  小遁哥

强烈建议使用具体命方法发送请求

发送get

axios.get('/user?ID=12345')

或着

axios.get('/user', {
    params: {
      ID: 12345
    }
  })

axios#get(url[, config])(查),delete(删)与其形式一样

发送post

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })

axios#post(url[, data[, config]])(改) ,put(增) 与其形式一样
相比于

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

不仅代码简洁,可读性野好。
根据 Content-Type 的类型,data可以不是普通对象

application/json

默认


image.png

application/x-www-form-urlencoded

普通表单提交

axios.post("/test/test/test2", qs.stringify({ bar: 123 }));

multipart/form-data

可以用于上传文件

    const params = new FormData();
    params.append("param1", "value1");
    params.append("param2", "value2");
    axios.post("/test/test/test2", params);
image.png
四种常见的 POST 提交数据方式
可以不指定,axios会自动判断

其实axiosPromise 的一种实现

console.log(axios.post("/test/test/test1"));
image.png

解决多个请求

 axios
      .all([
        new Promise((resolve, reject) => {
          resolve("success1");
        }),
        new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve("success2");
          }, 2000);
        }),
      ])
      .then(
        axios.spread((res1, res2) => {
          console.log(res1, res2);
        }),
      );

axios.all 请求都成功才算成功,有一个失败则失败,要和axios.spread 搭配使用

您有没有好奇,为啥没有Promiserace 方法

其实上述代码可以替换为:

    Promise.all([
      axios.post("/test/test/test2"),
      axios.post("/test/test/test1"),
    ]).then((r1, r2) => {
      console.log("res", r1, r2);
    });

同理race 可写为:

    Promise.race([
      axios.post("/test/test/test2"),
      axios.post("/test/test/test1"),
    ]).then((r1) => {
      console.log("res", r1);
    });

请求可以被取消

一些搜索不取消上一次的请求,响应时间大于用户做出其他操作的时间,可能看到一些奇怪的行为

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

axios配置概要

axios被设计成可以在nodejs中使用,官网上有些配置是只适用于nodejs

baseURL

公共前缀,用于生成最终的url

responseType

定义响应的数据类型 默认json,可以是arraybuffer, document, json, text, stream

onUploadProgress

得到上传进度

 onUploadProgress: function (progressEvent) {
 
  },

onDownloadProgress

得到下载进度

  onDownloadProgress: function (progressEvent) {

  }

transformRequest

自己处理发送的数据

    axios.post(
      "/test/test/test1",
      {
        content: "武汉加油!"
      },
      {
        headers: {
          "content-type": "application/json"
        },
        transformRequest: (data, headers) => {
          return JSON.stringify(data);
        }
      }

content-type 大小写不敏感

data 属性

发送的数据,最终发送的都是字符串,只是格式以及对应的解析方式不同
当没定义transformRequest 只能是FormData, File, Blob,string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams

headers

用于设置Request Headers,默认值{'X-Requested-With': 'XMLHttpRequest'}
x-requested-with 为 null,则为传统同步请求,为 XMLHttpRequest,则为 Ajax 异步请求。
x-requested-with的作用以及用法详解

timeout

相应超时时间,默认是0,不限制

withCredentials

默认false,跨域请求时是否携带Cookie,请求图片时不携带增加成功率,而登录时不携带则无法成功

validateStatus

返回状态码是多少时表示成功

  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

paramsSerializer

自定义序列化参数的方式

    axios.get(
      "/test/test/test1",

      {
        params: {
          content: "武汉加油!"
        },
        paramsSerializer: function(params) {
          return qs.stringify(params, { arrayFormat: "brackets" });
        }
      }

adapter

用于模拟响应

    axios
      .post(
        "/test/test/test1",
        {
          content: "武汉加油"
        },
        {
          adapter: function(config) {
            return new Promise((res, rej) => {
              const resInfo = {
                data: {
                  content: "必需的"
                },
                status: 200,
                statusText: "OK"
              };

              // 调用响应函数
              res(resInfo);
            });
          }
        }
      )
      .then(res => {
        console.log(res);
      });

这时便不会发送请求
config 是这个样子的


image.png

auth

Request Headers中会多出Authorization

    axios
      .post(
        "/test/test/test1",
        {
          content: "武汉加油"
        },
        {}
      )

修改配置

config 里面的属性都可以通过axios.defaults方式修改

axios.defaults.baseURL = 'https://api.example.com';

所有请求的Authorization默认值


axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

只对应post请求


axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

只有headers支持common和指定类型的设置

可以通过创建实例的方式指定配置

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

可以配置拦截器

请求时拦截

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

温馨提示,当代码逻辑与预期不符时,可以按照当前请求=>实例=>默认配置进行排查,以及排查拦截器的逻辑

下列拦截器逻辑可导致axios.all有请求失败也会走then方法,

axios.interceptors.response.use(
  function(response) {
    return response;
  },
  (error, response) => {
    if (error.response && error.response.status === 504) {
     
    } else {
      console.error(error);
    }
  }

上一篇 下一篇

猜你喜欢

热点阅读