asyc await

import axios from "axios";
import { notification } from "antd";
import Util from "./util";
import Config from "../config";

/**
 * 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 "axios"
 * @return {object}           An object containing either "data" or "err"
 */

const Req = async (url, options) => {
  const defaultOptions = {
    withCredentials: true,
    method: "GET",
    timeout: 15000,
    crossDomain: true,
    headers: {
      "Access-Control-Allow-Origin": "*",
      Accept: "application/json",
      "Content-Type": "application/json; charset=utf-8"
    }
    // data:{}
  };
  const combinedOptions = { ...defaultOptions, ...options }; //combined options

  /* if (
    combinedOptions.method === "POST" ||
    combinedOptions.method === "PUT" ||
    combinedOptions.method === "DELETE"
  ) {
    //set headers..
    if (!(combinedOptions.body instanceof FormData)) {
      //not formData, json
      combinedOptions.headers = {
        ...combinedOptions.headers,
       // Accept: "application/json",
       // "Content-Type": "application/json; charset=utf-8",
        // 'Access-Control-Allow-Origin': '*'
      };
      // combinedOptions.body = JSON.stringify(combinedOptions.body);
    } else {
      //formData...
      //   console.log("----------------request body json-------------------")
      // combinedOptions.body is FormData
      combinedOptions.headers = {
        ...combinedOptions.headers,
        //"content-type": "application/json",
        // 'Access-Control-Allow-Origin': '*'
      };
    }
  }  */

  //get auth...AUTH_TOKEN

  const AUTH_TOKEN = Util.getLocalItem(Config.localKey.userToken); // 模拟登录成功返回的Token
  if (AUTH_TOKEN) {
    combinedOptions.headers = {
      ...combinedOptions.headers,
      Authorization: AUTH_TOKEN
    };
  }

  console.log(combinedOptions);

  let Result = {};
  let Error = "";

  try {
    let response = await axios.request({
      url,
      // method: options && options.method ? options.method : 'GET', //default method is get
      // timeout: 15000, // http请求超时时间
      combinedOptions
    });

    if (response && response.status === 200) {
      Result = response.data;
      //   {
      //     errno: 0,
      //     errmsg: '',
      //     data: ...
      //   }   ctx.success();

      if ("errno" in Result && "errmsg" in Result && "data" in Result) {
        //thinkjs specific error  there is error...
        if (Result.errno > 0) {
          Error = Result.errmsg;
        } else {
          //no error
          Result = Result.data; //just return data...
        }
      }

      // do something with data
    } else {
      //something went wrong...response error...
      Error = `Thinkjs response error code# ${
        response.status
      }. error message# ${response.statusText}`;
    }
  } catch (err) {
    if (err.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(err.response.data);
      console.log(err.response.status);
      console.log(err.response.headers);

      Error = `Server response error code# ${
        err.response.status
      }. error message# ${err.response.data}`;
    } else if (err.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(err.request);
      Error = `Server request error ${err.request}`;
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log("Error", err.message);
      Error = `Error ${err.message}`;
    }
  }

  // debugger;

  if (Error !== "") {
    notification.error({
      message: "Error Occured!",
      description: Error
    });
    return {
      Result,
      Success: false
    };
  } else {
    return {
      Result,
      Success: true
    };
  }
};

export default Req;
复制代码

Reproduced in: https: //juejin.im/post/5d0b6ef1e51d455d877e0d35

Guess you like

Origin blog.csdn.net/weixin_34132768/article/details/93179310