1. 程式人生 > >react request.js 函數封裝

react request.js 函數封裝

內容類型 () contain lencod encode error 刪除 accept nco

1.request.js 函數封裝

import { Toast } from ‘antd-mobile‘;
import axios from ‘axios‘;
import store from ‘../store‘;
import { push } from ‘react-router-redux‘;
import qs from ‘qs‘;

// 請求路徑
const BaseUrl = ‘https://www.baidu.com/‘; // 主機及端口

//axios默認配置請求的api基礎地址
axios.defaults.baseURL = BaseUrl;
// axios.defaults.headers.post[‘Content-Type‘] = ‘application/x-www-form-urlencoded‘; // post 內容類型
// axios.defaults.headers.get[‘Content-Type‘] = ‘application/json;charset=utf-8‘; // get 內容類型
// axios.defaults.headers.post[‘Content-Type‘] = ‘multipart/form-data‘; // post 內容類型 formData 類型
axios.defaults.timeout = 30000; // 超時設置,超時進入錯誤回調,進行相關操作
axios.defaults.withCredentials = false; // 是否支持跨域cookie

const codeMessage = {
  200: ‘服務器成功返回請求的數據‘,
  201: ‘新建或修改數據成功。‘,
  202: ‘一個請求已經進入後臺排隊(異步任務)‘,
  204: ‘刪除數據成功。‘,
  400: ‘發出的請求有錯誤,服務器沒有進行新建或修改數據,的操作。‘,
  401: ‘用戶沒有權限(令牌、用戶名、密碼錯誤)。‘,
  403: ‘用戶得到授權,但是訪問是被禁止的。‘,
  404: ‘發出的請求針對的是不存在的記錄,服務器沒有進行操作‘,
  406: ‘請求的格式不可得。‘,
  410: ‘請求的資源被永久刪除,且不會再得到的。‘,
  422: ‘當創建一個對象時,發生一個驗證錯誤。‘,
  500: ‘服務器發生錯誤,請檢查服務器‘,
  502: ‘網關錯誤‘,
  503: ‘服務不可用,服務器暫時過載或維護‘,
  504: ‘網關超時‘,
};

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const errortext = codeMessage[response.status] || response.statusText;
  // 提示框
  Toast.info(`請求錯誤 ${response.status}: ${response.url}`,1)
  const error = new Error(errortext);
  error.name = response.status;
  error.response = response;
  throw error;
}


/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  const defaultOptions = {
    credentials: ‘include‘,
  };
  const newOptions = { ...defaultOptions, ...options };
  if (
    newOptions.method === ‘POST‘ ||
    newOptions.method === ‘PUT‘ ||
    newOptions.method === ‘DELETE‘
  ) {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: ‘application/json‘,
        ‘Content-Type‘: ‘application/x-www-form-urlencoded‘,
        ...newOptions.headers,
      };
      newOptions.data = qs.stringify(newOptions.body);
      newOptions.body = JSON.stringify(newOptions.body);
    } else {
      // newOptions.body is FormData
      newOptions.headers = {
        Accept: ‘application/json‘,
        ...newOptions.headers,
      };
    }
  }

  return axios(url, newOptions)
    .then(checkStatus)
    .then((response) => {
      // 成功的回調
      if (newOptions.method === ‘DELETE‘ || response.status === 204) {
        return response.text();
      }
      return response.data;
    })
    .catch((e) => {
      // 失敗的回調
      const { dispatch } = store;
      const status = e.name;
      if (status === 401) {
        dispatch({
          type: ‘login/logout‘,
        });
        return;
      }
      if (status === 403) {
        dispatch(push(‘/exception/403‘));
        return;
      }
      if (status <= 504 && status >= 500) {
        dispatch(push(‘/exception/500‘));
        return;
      }
      if (status >= 404 && status < 422) {
        dispatch(push(‘/exception/404‘));
      }
    });
}

2.註:向後臺傳遞數組的方法

需要在qs的方法中設置它的indicesfalse即可,如:

qs.stringify({ a: [‘b‘, ‘c‘, ‘d‘] }, { indices: false });

.

react request.js 函數封裝