axios备忘录(post,get,拦截器,取消请求,config配置)

154 阅读3分钟

axios 发送请求(常用)

1. axios.request(config);
axios({
  method: "post",
  url: "/user/12345",
  data: {
    firstName: "Fred",
    lastName: "Flintstone",
  },
  timeout: 1000,
  //   ...//其他相关配置
});
2. axios.get(url[, config])
axios.get("demo/url", {
  params: {
    id: 123,
    name: "Henry",
  },
  timeout: 1000,
  //   ...//其他相关配置
});
3. axios.post(url[, data[, config]])
axios.post(
  "demo/url",
  {
    id: 123,
    name: "Henry",
  },
  {
    timeout: 1000,
    // ...//其他相关配置
  }
);

对 axios 进行默认配置

1. 对所有axios进行默认配置
 axios.defaults.method = 'GET';//设置默认的请求类型为 GET
 axios.defaults.baseURL = 'http://localhost:3000';//设置基础 URL
 axios.defaults.params = {id:100};
 axios.defaults.timeout = 3000;//
 btn.onclick = function () {
   axios({
     url: "/posts",
   }).then((response) => {
     console.log(response);
   });
 };
 2. 生成一个新的axios实例,该实例为拥有默认配置的axios
 const Axios = axios.create({
   timeout: 3000,
   params: { id: 100 },
   baseURL: "http://localhost:3000",
   method: "GET",
 });

 btn.onclick = function () {
   Axios({
     url: "/posts",
   }).then((response) => {
     console.log(response);
   });
 };

设置请求拦截器

axios.interceptors.request.use(
  function (config) {
    console.log("请求拦截器 成功 - 1号");
    //修改 config 中的参数
    config.params = { a: 100 };
    return config;
  },
  function (error) {
    console.log("请求拦截器 失败 - 1号");
    return Promise.reject(error);
  }
);
axios.interceptors.request.use(
  function (config) {
    console.log("请求拦截器 成功 - 2号");
    //修改 config 中的参数
    config.timeout = 2000;
    return config;
  },
  function (error) {
    console.log("请求拦截器 失败 - 2号");
    return Promise.reject(error);
  }
);
// 设置响应拦截器
axios.interceptors.response.use(
  function (response) {
    console.log("响应拦截器 成功 1号");
    return response.data;
    // return response;
  },
  function (error) {
    console.log("响应拦截器 失败 1号");
    return Promise.reject(error);
  }
);
axios.interceptors.response.use(
  function (response) {
    console.log("响应拦截器 成功 2号");
    return response;
  },
  function (error) {
    console.log("响应拦截器 失败 2号");
    return Promise.reject(error);
  }
);
// 运行结果为
//  请求拦截器 成功 - 2号
//  请求拦截器 成功 - 1号
//  响应拦截器 失败 1号
//  响应拦截器 失败 2号
//  请求拦截器被加入 chain时使用了数组的unshift , 响应拦截器 被加入 chain时使用了数组的push

请求取消

//获取按钮
const btns = document.querySelectorAll("button");
//2.声明全局变量
let cancel = null;
//发送请求
btns[0].onclick = function () {
  //检测上一次的请求是否已经完成
  if (cancel !== null) {
    // cancel();  //取消上一次的请求
    return; //阻止下一次的请求
  }
  axios({
    method: "GET",
    url: "http://localhost:3000/posts",
    //1. 添加配置对象的属性
    cancelToken: new axios.CancelToken(function (c) {
      //3. 将 c 的值赋值给 cancel
      cancel = c;
    }),
  }).then((response) => {
    console.log(response);
    //将 cancel 的值初始化
    cancel = null;
  });
};
//绑定第二个事件取消请求
btns[1].onclick = function () {
  cancel();
};

config 能进行那些配置?

config = {
  //请求发给谁
  url: "/user",
  //请求类型
  method: "get", // default
  //基础路径 实际请求路径是 baseURL + url
  baseURL: "https://some-domain.com/api/",
  //对请求的数据做一些处理,然后将处理后的结果发送给服务器
  transformRequest: [
    function (data, headers) {
      // Do whatever you want to transform the data

      return data;
    },
  ],
  //对响应的数据做一些处理,然后将处理后的结果返回给用户
  transformResponse: [
    function (data) {
      // Do whatever you want to transform the data

      return data;
    },
  ],
  //请求头信息
  headers: { "X-Requested-With": "XMLHttpRequest" },
  // params 会被转换成 ?ID=12345&name=Tom 然后加在路径后面,请求的时候一起带给服务器
  params: {
    ID: 12345,
    name: Tom,
  },
  //格式化 params 对象 将{ID: 12345,name:Tom } 转换为需要的格式
  paramsSerializer: function (params) {
    return Qs.stringify(params, { arrayFormat: "brackets" });
  },
  //传递参数
  data: {
    firstName: "Fred",
  },
  //传递参数
  data: "Country=Brasil&City=Belo Horizonte",
  //超时时间 单位 ms 超时的话会取消
  timeout: 1000, // default is `0` (no timeout)
  //跨域时是否携带 cookie
  withCredentials: false, // default
  adapter: function (config) {},
  //基础验证
  auth: {
    username: "janedoe",
    password: "s00pers3cret",
  },
  //返回回来的数据格式
  responseType: "json", // default
  //返回回来数据的字符集编码
  responseEncoding: "utf8", // default
  //为了安全,防止跨站攻击
  xsrfCookieName: "XSRF-TOKEN", // default
  //为了安全,防止跨站攻击
  xsrfHeaderName: "X-XSRF-TOKEN", // default
  //上传的时候执行回调
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
  //下载的时候执行回调
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
  //设置 http 响应体的最大尺寸,单位是 字节
  maxContentLength: 2000,
  //设置 http 请求体的最大尺寸
  maxBodyLength: 2000,
  //判断响应是否成功的条件 validateStatus: function (status) {
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },
  //最大跳转次数
  maxRedirects: 5, // default
  socketPath: null, // default
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
  //设置代理
  proxy: {
    protocol: "https",
    host: "127.0.0.1",
    port: 9000,
    auth: {
      username: "mikeymike",
      password: "rapunz3l",
    },
  },
  //取消请求的设置
  cancelToken: new CancelToken(function (cancel) {}),
  signal: new AbortController().signal,
  decompress: true, // default
  insecureHTTPParser: undefined, // default
  transitional: {
    silentJSONParsing: true, // default value for the current Axios version
    forcedJSONParsing: true,
    clarifyTimeoutError: false,
  },
};