移动端 - 另一种axios

import axios from "axios";
import Cookies from "js-cookie";
import { Toast } from "vant";

const NODE_ENV = process.env.NODE_ENV;
const BASEURL =
  NODE_ENV === "development" ? "/api" : "线上地址"; 
Toast.setDefaultOptions({ // 显示延迟 duration: 2500 }); const tip = message => { Toast.fail(message || "请求超时"); }; const errorHandler = (status, msg) => { switch (status) { case 404: tip("请求地址不存在"); break; case 500: tip(msg || "无法请求到后台服务"); break; default: tip(msg); } }; const http = axios.create({ baseURL: BASEURL, timeout: 15000, // 允许自动携带cookie withCredentials: true }); // 添加请求拦截器 http.interceptors.request.use( function(config) { let token = Cookies.get("X-Auth-Token") || ""; if (token) { config.headers["X-Auth-Token"] = token || ""; } return config; }, function(error) { return Promise.reject(error); } ); // 添加响应拦截器 http.interceptors.response.use( response => { if (response.status === 200) { return Promise.resolve(response.data); } else { return Promise.reject(response.data); } }, error => { let { response } = error; if (response) { let { message, status } = response.data; console.log(response.status, message); if (message == "token无效") { Cookies.remove("X-Auth-Token"); location.reload(); } errorHandler(response.status, message || "连接超时"); } else { // 处理断网等 } return Promise.reject(error); } ); export default http;

next ( 封装请求 格式 - baseRequest.js )

import http from "./http";
import qs from "qs";

function postQuery(url, v) {
  let qs_v = v ? `?${qs.stringify(v)}` : "";
  return http.post(`${url}${qs_v}`);
}

function postParams(url, v) {
  return http.post(url, {
    ...v
  });
}

function postFileParams(url, v) {
  return http.post(url, v, {
    headers: {
      "Content-Type": "multipart/form-data"
    }
  });
}

function getQuery(url, v) {
  let qs_v = v ? `?${qs.stringify(v)}` : "";
  return http.get(`${url}${qs_v}`);
}

function axiosHttp(data) {
  if (!data) return;
  return http(data);
}

function postFileIdcard(url, v) {
  return http.post(url, v, {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  });
}

export {
  postQuery,
  postParams,
  getQuery,
  postFileParams,
  axiosHttp,
  postFileIdcard
};

next (封装接口 - index.js)

import {
  postQuery,
  postParams,
  getQuery,
  postFileParams,
  postFileIdcard
} from " ./http/baseRequest.js";

function getMyrCode(v) {
  return postParams("/Visitor/qrCode", v);
}

export {
getMyrCode, };

next( 请求接口  - 页面中)

   
     import { getMyQrCode } from "@/api/index";

    let params = { id: 282 }; getMyQrCode(params).then(res => { let { code, data, message } = res; if (code == 0) { } else { } });

 

移动端 - 另一种axios

上一篇:Build offline apps with new PowerApps capabilities


下一篇:Android 应用程序构建实战+原理精讲