umijs / umi-request

A request tool based on fetch.
2.21k stars 335 forks source link

请求设置 requestType: 'form' 无效 #330

Closed xyy7260 closed 1 year ago

xyy7260 commented 1 year ago
import { request } from '@umijs/max';

 export async function CustomUploadImgApi(arrayFile: any, options?: { [key: string]: any }) {
  // const formData = new FormData();
  // arrayFile.forEach(function (item: any) {
  //   formData.append(item.filename, item.file);
  // });
  const formData = new FormData();
  formData.append('username', 'john');
  formData.append('email', 'john@example.com');

  return request<APIRequest.requestBody>('/api/proxy/image/upload', {
    method: 'POST',
    body: formData,
    requestType: 'form',
    // headers: {
    //   'Content-Type': 'multipart/form-data',
    // },
    ...(options || {}),
  });
}
image image

按照文档方式设置 requestType: 'form' 请求体中却没有发现 'Content-Type': 'multipart/form-data',

requestErrorConfig.ts 文件如下


import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import { history } from '@umijs/max';

import { message, notification } from 'antd';

// 错误处理方案: 错误类型
enum ErrorShowType {
  SILENT = 0,
  WARN_MESSAGE = 1,
  ERROR_MESSAGE = 2,
  NOTIFICATION = 3,
  REDIRECT = 9,
}
interface ResponseStructure {
  success: boolean;
  data: any;
  errorCode?: number;
  message?: string;
  showType?: ErrorShowType;
}

export const errorConfig: RequestConfig = {
  // 错误处理: umi@3 的错误处理方案。
  errorConfig: {
    // 错误抛出
    errorThrower: (res: any) => {
      const { success, message } = res as unknown as ResponseStructure;
      if (!success) {
        const error: any = new Error(message);
        error.name = message;
        error.info = res;
        throw error; // 抛出自制的错误
      }
    },
    // 错误接收及处理
    errorHandler: (error: any, opts: any) => {
      if (opts?.skipErrorHandler) throw error;
      // 我们的 errorThrower 抛出的错误。
      if (error.name === 'BizError') {
        const errorInfo: ResponseStructure | undefined = error.info;
        if (errorInfo) {
          const { errorCode } = errorInfo;
          switch (errorInfo.showType) {
            case ErrorShowType.SILENT:
              // do nothing
              break;
            case ErrorShowType.WARN_MESSAGE:
              message.warning(errorInfo.message);
              break;
            case ErrorShowType.ERROR_MESSAGE:
              message.error(errorInfo.message);
              break;
            case ErrorShowType.NOTIFICATION:
              notification.open({
                description: errorInfo.message,
                message: errorCode,
              });
              break;
            case ErrorShowType.REDIRECT:
              // TODO: redirect
              break;
            default:
              message.error(errorInfo.message);
          }
        }
      } else if (error.response) {
        // Axios 的错误
        // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
        message.error(`error: ${error.message}`);

        if (error.response?.status === 401) {
          window.localStorage.clear();
          history.push('/user/login');
        }
      } else if (error.request) {
        // 请求已经成功发起,但没有收到响应
        // \`error.request\` 在浏览器中是 XMLHttpRequest 的实例,
        // 而在node.js中是 http.ClientRequest 的实例
        message.error('None response! Please retry.');
      } else {
        // 发送请求时出了点问题
        // message.error('Request error, please retry.');
      }
    },
  },

  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      console.log(config);
      return { ...config };
    },
  ],
  // 响应拦截器
  responseInterceptors: [
    (response: any) => {
      // 拦截响应数据,进行个性化处理
      const { data } = response as unknown as ResponseStructure;
      // console.log(response.config.url, response);
      if (data?.success === false) {
        switch (response.config.url) {
          case '/api/auth/login':
            // message.error(I18n('page.login.error'));
            // do nothing
            break;
          default:
            message.error(data.message);
        }
      }
      return response;
    },
  ],
};
xyy7260 commented 1 year ago

这里