发送请求的封装传参

原生:axios.get(url, { params, headers })
axios({
  method:'post',
  url: requestUrl,
  params
})

封装:export function getAreaList(params) {
  return request({
    url: api.AreaList,
    method: 'get',
    params,
  })
}
//get请求传递的是参数是放在对象里所以封装只需params直接使用、

原生:axios.post(url, params, { headers })
axios({
  method:'post',
  url: requestUrl,
  data: {
  }
})
封装:export function getAreaList(params) {
  return request({
    url: "/wechat/unbind",
    method: "post",
    data: params,
  })
}

import axios from "axios";
import { Notification, MessageBox, Message } from "element-ui";
import store from "../store";
import appConfig from "../../app.config";
import Qs from "qs";
// 创建axios实例
const service = axios.create({
  baseURL: appConfig.apiPath, // api的base_ur
  timeout: 30000, // 请求超时时间
});
service.defaults.headers.common["token"] = appConfig.apiToken;
// request拦截器
service.interceptors.request.use(
  (config) => {
    // if (config.method == 'post') {
    //   config.headers["Content-Type"] =
    //     "application/json;charset=UTF-8";
    // }
    // config.headers["Authorization"] = store.state.user.token;
    // if (config.url == "/oss/uploadPicture") {
    //   config.headers["Content-Type"] =
    //     "application/x-www-form-urlencoded; charset=UTF-8";
    //   config.transformRequest = [
    //     (data) => {
    //       data = Qs.stringify(data);
    //       return data;
    //     },
    //   ];
    // }
    return config;
    console.log(config)
  },
  (error) => {
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  (response) => {
    /**
     * response.data是抛错代码 可结合自己业务进行修改
     */
    // console.log(response.data);
    const res = response.data;
    if (res.code == 400) {
      Message({
        message: response.data.msg,
        type: "error",
      });
      return response.data;
    } else if (res.code == 401) {
      Message({
        message: response.data.msg,
        type: "error",
      });
      return response.data;
    } else {
      return response.data;
    }
  },
  (error) => {
    console.log("错误信息", error);
    console.log("错误信息", error.response);
    if (
      error.code == "ECONNABORTED" &&
      error.message.indexOf("timeout") != -1
    ) {
      console.log("接口请求超时!");
      return "";
    }
    if (error.response.status === 401) {
      console.log("登录过期");
      return;
    } else if (error.response.status === 503 || error.response.status === 502) {
      console.log("服务器错误,请联系管理员!");
      return;
    }

    return Promise.reject(error);
  }
);

export default service;

上一篇:scrapy解析html返回response


下一篇:Flask中的request和response