| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- // ant-design-pro request.js file with MIT license
- import "whatwg-fetch";
- import router from "@/router";
- import { LOGIN_ROUTER } from "@/router/name";
- /**
- * @description error
- * @typedef {Object} StatusException
- * @property {string} name status code
- * @property {string} message 消息
- * @property {{code:string,message:string}} response 返回值
- */
- /**
- * 判断是否抛异常
- * @param response
- * @returns {*}
- * @throws StatusException
- */
- function checkStatus(response) {
- if (response.status >= 200 && response.status < 300) {
- return response;
- }
- const error = new Error(response.message);
- 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 {{method:string,body}} [options] The options we want to pass to "fetch"
- * @return {Promise<*>} An object containing either "data" or "err"
- * @throws StatusException
- */
- export default async 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/json; charset=utf-8",
- ...newOptions.headers
- };
- newOptions.body = JSON.stringify(newOptions.body);
- } else {
- // newOptions.body is FormData
- newOptions.headers = {
- Accept: "application/json",
- ...newOptions.headers
- };
- }
- }
- const response = await fetch(url, newOptions);
- try {
- checkStatus(response);
- } catch (e) {
- if (e.name !== 418) {
- router.push({ name: LOGIN_ROUTER });
- } else {
- throw new Error(e);
- }
- }
- if (newOptions.method === "DELETE" || response.status === 204) {
- return response.text();
- }
- return response.json();
- }
|