react 封裝axios


1.進入項目,安裝axios

npm install axios

2. 安裝antd

npm install antd --save

 

3.對axios二次封裝

 1.  新建loading.css文件。

#loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(250, 250, 250, 0.65);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  z-index: 2000;
}

 

 2. 新建 axios.js文件,並引入 loading.css 文件。

import axios from 'axios'
import { message } from 'antd';
import { Spin } from 'antd';
import React from 'react';
import ReactDOM from 'react-dom';
import '../css/loading.css';


// 默認域名 
// axios.defaults.baseURL = "http://10.26.4.123:8080/api/";
// 配置請求頭
axios.defaults.headers["Content-Type"] = "application/json";
// 響應時間
axios.defaults.timeout = 10000;
//請求攔截器
axios.interceptors.request.use(
  config => {
    getUser();//獲取用戶信息
    showLoading();//顯示加載動畫
    if(user){
      // 設置統一的請求header
      config.headers.authorization = user.token //授權(每次請求把token帶給后台)
    }
    config.headers.platform = user ? user.platform : 8 //后台需要的參數
    return config;
  },
  error => {
    hideLoading();//關閉加載動畫
    return Promise.reject(error);
  }
);

//響應攔截器
axios.interceptors.response.use(
  response => {
    hideLoading();//關閉加載動畫
    if(response.data.returnCode === '0014'){ // 登錄失效
      localStorage.clear(); // 清除緩存
      message.success({
        content: '您的登錄已經失效,請重新登錄',
        duration: 2
      });
      setTimeout(() => {
        //讓用戶從新回到登錄頁面
        window._ROUTER_.push('/login');//router是在頂級入口app.js文件定義了window._ROUTER_ = this.props.history;
      }, 2000)
    }
    return response;
  },
  error => {
    hideLoading();//關閉加載動畫
    return Promise.resolve(error.response);
  }
);

// 處理請求返回的數據
function checkStatus(response) {
  return new Promise((resolve, reject) => {
    if(response && (response.status === 200 || response.status === 304 || response.status === 400)){
      resolve(response.data);
    }else{
      message.success({
        content: '網絡異常,請檢查網絡連接是否正常!',
        duration: 2
      });
    }
  });
}

export default {
  post(url, params) {
    return axios({
      method: "post",
      url,
      data: params
    }).then(response => {
      return checkStatus(response);
    });
  },
  get(url, params) {
    return axios({
      method: "get",
      url,
      params,
    }).then(response => {
      return checkStatus(response);
    });
  }
};

// 獲取緩存中的用戶信息, 這是接口返回的信息。
var user;
function getUser() {
  if (localStorage.getItem('userInfo')) {
    user = JSON.parse(localStorage.getItem('userInfo'));
  }
}

// 顯示加載動畫
function showLoading () {
  let dom = document.createElement('div')
  dom.setAttribute('id', 'loading')
  document.body.appendChild(dom)
  ReactDOM.render(<Spin tip="加載中..." size="large"/>, dom)
}
// 隱藏加載動畫
function hideLoading () {
  document.body.removeChild(document.getElementById('loading'))
}

 

在使用的頁面引入axios。

import axios from '../../assets/js/axios'
loginBtn =()=> {
    axios.post(MEMBER_SIGNIN,this.state.form).then((res) => {
      if (res.returnCode === '200') {
        message.success(res.msg);
      }
    })
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM