zoukankan      html  css  js  c++  java
  • react axios

    • 安装axios
    npm install axios
    
    • 建立请求js
    import axios from "axios";
    import { Component } from "react";
    
    let base = "/api";
    
    // 请求前拦截
    axios.interceptors.request.use(
      config => {
        return config;
      },
      err => {
        console.log("请求超时");
        return Promise.reject(err);
      }
    );
    
    // 返回后拦截
    axios.interceptors.response.use(
      data => {
        return data;
      },
      err => {
        if (err.response.status === 504 || err.response.status === 404) {
          console.log("服务器被吃了⊙﹏⊙∥");
        } else if (err.response.status === 401) {
          console.log("登录信息失效⊙﹏⊙∥");
        } else if (err.response.status === 500) {
          console.log("服务器开小差了⊙﹏⊙∥");
        }
        return Promise.reject(err);
      }
    );
    
    // @RequestBody请求
    const postRequestBody = (url, params) => {
      return axios({
        method: "post",
        url: `${base}${url}`,
        data: params,
        headers: {
          "Content-Type": "application/json",
          charset: "utf-8"
        }
      });
    };
    
    // @RequsetParam请求
    const postRequestParam = (url, params) => {
      return axios({
        method: "post",
        url: `${base}${url}`,
        data: params,
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=
                encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
            }
            return ret;
          }
        ],
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      });
    };
    
    const get = url => {
      return axios({
        method: "get",
        url: `${base}${url}`
      });
    };
    
    const multiple = function(requsetArray, callback) {
      axios.all(requsetArray).then(axios.spread(callback));
    };
    
    Component.prototype.get = get;
    Component.prototype.postRequestBody = postRequestBody;
    Component.prototype.postRequestParam = postRequestParam;
    Component.prototype.multiple = multiple;
    
    
    • index.js引入封装js
    import "./axios/http";


    作者:ChangLau
    链接:https://www.jianshu.com/p/79816fa9c54f
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    filter&map&reduce
    Linux通过进程ID查看文件路径
    PyCharm使用最多也最常用默认快捷键介绍
    Python中的深浅拷贝
    类加载器&反射
    Java web.xml 配置详解
    SpringMVC + Spring + MyBatis 整合 + Spring shrio + easyUI + 权限管理框架,带shrio session和shrio cache集群实现方案
    JAVA大数据数组排序
    高访问量WEB开发中的架构模式,学习从点滴开始
    WEB项目会话集群的三种办法
  • 原文地址:https://www.cnblogs.com/hanzeng1993/p/12176581.html
Copyright © 2011-2022 走看看