#react 之ant design Pro 學習研究#----後臺交互

#後臺請求json 格式 / FormData 格式json

import fetch from 'dva/fetch';
import fetchJsonp from 'fetch-jsonp';
import { notification } from 'antd';
import { routerRedux } from 'dva/router';
import store from '../index';

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;
  notification.error({
    message: `請求錯誤 ${response.status}: ${response.url}`,
    description: errortext,
  });
  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') {
      if (!(newOptions.body instanceof FormData)) {
        newOptions.headers = {
          Accept: 'application/json',
          'Content-Type': 'application/json; charset=utf-8',
          ...newOptions.headers,
        };
        newOptions.body = JSON.stringify(newOptions.body);
      } else {
        // newOptions.body is FormData
        // newOptions.headers = {
        //   "Content-Type": "multipart/form-data",
        //  // ...newOptions.headers,
        // };
        //newOptions = {...options}
        //newOptions.headers = {"Content-Type": "multipart/form-data"}
        return requestcore(url,options);

      }
    }


  return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => {
      if (newOptions.method === 'DELETE' || response.status === 204) {
        return response.text();
      }
      return response.json();
    })
    .catch(e => {
      const { dispatch } = store;
      const status = e.name;
      if (status === 401) {
        dispatch({
          type: 'login/logout',
        });
        return;
      }
      if (status === 403) {
        dispatch(routerRedux.push('/exception/403'));
        return;
      }
      if (status <= 504 && status >= 500) {
        dispatch(routerRedux.push('/exception/500'));
        return;
      }
      if (status >= 404 && status < 422) {
        dispatch(routerRedux.push('/exception/404'));
      }
    });
}

 function requestcore(url, options) {

  const newOptions = {  ...options };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {

      // newOptions.body is FormData
      // newOptions.headers = {
      //   "Content-Type": "multipart/form-data",
      //  // ...newOptions.headers,
      // };
     // newOptions.headers = {"Content-Type": "multipart/form-data"}

    }
  return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => {
      if (newOptions.method === 'DELETE' || response.status === 204) {
        return response.text();
      }
      return response.json();
    })
    .catch(e => {
      const { dispatch } = store;
      const status = e.name;
      if (status === 401) {
        dispatch({
          type: 'login/logout',
        });
        return;
      }
      if (status === 403) {
        dispatch(routerRedux.push('/exception/403'));
        return;
      }
      if (status <= 504 && status >= 500) {
        dispatch(routerRedux.push('/exception/500'));
        return;
      }
      if (status >= 404 && status < 422) {
        dispatch(routerRedux.push('/exception/404'));
      }
    });
}

request 處理全部請求後端

#後端promise

public ServiceResponse login(@RequestBody UserInfo info)

#附件採用FormData 包裝參數,調用requestcore服務器

const formData = new FormData()
           formData.append('file', values.template.file, values.template.file.name);
           formData.append('billTypeId',values.billType);
           formData.append('name',values.name);
           formData.append('number',values.number);
           formData.append('remark',values.remark);
          dispatch({
            type: 'billTable/add',
            payload: formData,
            callback: (res) => {
              if(res.meta.status !== '000000' ) {
                message.error("添加業務用表失敗,請稍後再試!"+res.data.alert_msg)
              }else{
                //
                message.success('添加成功');
                form.resetFields();
                handleModalVisible(false);

                dispatch({
                  type: 'billTable/fetch',
                  payload: {
                    page: 1,
                    pageSize: 10,
                  }
                });
              }
            },
          });

不用增長headers 參數,否則後臺會報錯antd

#後端app

public ServiceResponse addBillTable(BillTableInfo paramObj, HttpServletRequest req, MultipartFile file)

不用增長@RequestBody 註解異步

相關文章
相關標籤/搜索