axios中的那些请求

一般axios是需要封装的,编写http.js进行统一的管理。

import axios from "axios";

............................

let http2 = axios.create({
  baseURL: ".........................................",
  timeout: 5 * 1000
});

http2.interceptors.request.use(
  function(config) {
    console.log(config);
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

http2.interceptors.response.use(
  function(response) {
    return response;
  },
  function(error) {
    return Promise.reject(error);
  }
);
function getHttpInstanse(flag) {
  if (flag === 1) {
    return http1;
  } else if (flag === 2) {
    return http2;
  } else {
    return http3;
  }
}

export default getHttpInstanse;

对于简单的get请求,几乎使用拼接的方法就可以满足条件了

this.$http(1)
        .get(
          `........?code=${url}&device=${this.device}`
        )
        .then(res => {
        ..........................
        })
        .catch(err => {
          console.log(err);
          that.$toast.fail("网络错误");
        });

对于post请求,要稍微复杂一点,比如像云端规定了是参数param的,那么直接用param字段

this.$http(1)({
        url: ".........",
        method: "get",
        params: {
          searchType: this.tabIndex === "1" ? "1" : "2",
          ownerCode: this.ownerCode
        }
        // headers: {
        //   "Content-Type": "application/json;charset=utf-8",
        //   Authorization: this.jsonStr.token,
        //   channelId: "JHK20210531ZDSYKX00113"
        // }
      }).then(res => {
       ..........
      });

如果云端告诉你,他接收的是body里的东西,那么使用的是data字段,鉴于现在大多使用的是jsonString的结构,那么大概率在传输之前需要转换一下格式:

this.$http(2)({
        url: "...",
        method: "post",
        headers: {
          "Content-Type": "application/json;charset=utf-8"
        },
        data: JSON.stringify({
          curveUid: this.curveUid,
          requestSource: 1,
          cookbookName: this.cookbookName,
          accessToken: this.getToken
        })
      })
        .then(res => {
          ...
        })
        .catch(erro => {
          ...
        });

再如果有传输文件的需求,或者其他表单的需求,那么就需要用到formData表单传输了,代码中需要先new一个FormData对象,然后将其放入data中,同时要注意将请求header改一下:

let formData = new FormData();
      formData.append("files", file);
      ...
      formData.append("menu", JSON.stringify(menu));
      formData.append("accessToken", this.getToken);
     
      this.$http(2)({
        url: "...",
        method: "post",
        data: formData,
        headers: {
          "Content-Type": "form-data"
        }
      })
        .then(res => {
        
        })
        .catch(erro => {
       
        });

你可能感兴趣的:(axios中的那些请求)