基于Fetch封装Requst工具类

安装依赖

$ yarn add isomorphic-fetch

新建utils/Requst.js 文件

import fetch from 'isomorphic-fetch'

// this is base_url, you can set webpack
/***
new webpack.DefinePlugin({
    'process.env': {
        'NODE_ENV': JSON.stringify(env),//production development
        'BASE_API_ENDPOINT' : JSON.stringify('') // here , watch env
    },        
}),
***/
// or set .env and .env.production
/*** 
BASE_API_ENDPOINT=http://192.**.1.**:8849  //  inner .env
BASE_API_ENDPOINT=http://192.**.4.**:8849  //  inner .env.production
***/
const BASE_URL = process.env.BASE_API_ENDPOINT

// content-type
const ContentType = {
  JSON: "application/json; charset=UTF-8",
  FORM: "application/x-www-form-urlencoded; charset=UTF-8"
}

// Http method
const HttpMethod = {
  GET : "GET",
  POST : "POST",
  PUT : "PUT",
  PATCH : "PATCH",
  DELETE : "DELETE"
}

// common check
const checkStatus = response => {
  if(Object.is(200, response.status)) return response.json()
  throw new Error(response.status)
}

// common error
const handleError = promise => {
  return promise
    .then(response => checkStatus(response))
    .catch((error) => {
      // const { message: status } = error
      // TODO you can handle the common error here
      throw new Error('服务器发生未知错误')
    })
}

// handle url
const getUrl = (url) => {
  if(url.startsWith('http://') || url.startsWith('https://')) return url
  return `${BASE_URL}${url}`
}

// token header
export const getTokenHeaders = () => {
  // TODO get the token permission request
  // const token = Cookies.get(COOKIE_TOKEN)
  const token = ''
  return {
    "Accept": ContentType.JSON,
    "Content-Type": ContentType.JSON,
    "Token": token
  }
}

// common header
const getHeaders = () => {
  return {
    "Accept": ContentType.JSON,
    "Content-Type": ContentType.JSON
  }
}

export default {
  /** GET请求
   * @param url: string
   * @param params {}
   * @param headers
   * @returns Promise
   */
  get: function (url, params, headers = getHeaders()) {
    if (params) {
      let paramsArray = []
      // encodeURIComponent
      Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
      if (url.search(/\?/) === -1) {
        url += '?' + paramsArray.join('&')
      } else {
        url += '&' + paramsArray.join('&')
      }
    }
    const promise = fetch(getUrl(url), {
      method : HttpMethod.GET,
      headers: headers
    })
    return handleError(promise)
  },
  /** POST请求  FormData 表单数据
   * @param url
   * @param formData
   * @param headers
   * @returns Promise
   */
  postForm: function (url, formData, headers = getHeaders()) {
    const promise = fetch(getUrl(url), {
      method : HttpMethod.POST,
      headers: headers,
      body : formData
    })
    return handleError(promise)
  },
  /*** POST 请求
   * @param url
   * @param params 参数,这里的参数格式是:{param1: 'value1',param2: 'value2'}
   * @param headers
   * @returns Promise
   * */
  postJSON: function (url, params, headers = getHeaders()) {
    const promise = fetch(getUrl(url), {
      method : HttpMethod.POST,
      headers: headers,
      body : JSON.stringify(params)
    })
    return handleError(promise)
  },
  /*** PATCH 请求
   * @param url
   * @param params 参数,这里的参数格式是:{param1: 'value1',param2: 'value2'}
   * @param headers
   * @returns Promise
   * */
  patchJSON: function (url, params, headers = getHeaders()) {
    const promise = fetch(getUrl(url), {
      method : HttpMethod.PATCH,
      headers: headers,
      body : JSON.stringify(params)
    })
    return handleError(promise)
  },
}

外部servies导入方式

// 比如新建services/Home/index.js 文件夹

// you can override the default parameters.
import Request, { getTokenHeaders } from '../../utils/Request'

// 当然如果出现单个模块不一样的域名, 你也可以硬编码不一样的域名地址
// production api
let DEMO_URL = 'http://192.***.*.23:***'
// development api
if (process.env.NODE_ENV !== 'production') {
  DEMO_URL = 'http://192.***.*.45:***'
}

export default {
  postFeetList: function () {
    return Request.postJSON(`/api/intent/give-me-five`)
  },
  patchFeedStatus: function ({ id, status}) {
    return Request.patchJSON(`/api/feeds/${id}`, {status}, getTokenHeaders())
  },
  // of course, you can add http
 getDemoList: function () {
    return Request.postJSON(`${DEMO_URL}/api/intent/give-me-five`)
  }, 
}

你可能感兴趣的:(React,JS工具类,ECMAScript6)