request.js 1.42 KB
class Request {
  DOMAIN = '/cwq'
  constructor(_request_) {
    this.DOMAIN = _request_ ? _request_.baseURL : this.DOMAIN
  }
  get (url, params, returnAll) {
    return this.request('GET', url, params, returnAll)
  }
  post (url, params, returnAll) {
    return this.request('POST', url, params, returnAll)
  }
  request (method, url, params, returnAll) {
    var requestConfig = {
      headers: {
        // 'Content-Type': method == 'GET' ? 'application/json' : 'application/x-www-form-urlencoded; charset=UTF-8'
        'Content-Type': 'application/json'
      },
      method
    }
    params.req.corporateGroupName = '广汇'
    const { reportParams } = window.vm.$store.state.app
    if (reportParams) {
      if (reportParams.brand) params.req.brandName = reportParams.brand.name
    }
    if (method === 'GET') {
      var paramsArray = []
      Object.keys(params.req).forEach(key => paramsArray.push('req.' + key + '=' + params.req[key]))
      if (url.search(/\?/) === -1) {
        url += '?' + paramsArray.join('&')
      } else {
        url += '&' + paramsArray.join('&')
      }
    }

    if (method === 'POST') {
      Object.defineProperty(requestConfig, 'body', {
        value: JSON.stringify(params)
      })
    }

    return window
      .fetch(this.DOMAIN + `/${url}`, requestConfig)
      .then(res => {
        return res.json()
      })
    // .catch(error => {
    //   alert(error)
    // })
  }
}

export default Request