// src->utils->service.js
import { Message } from 'element-ui'
import axios from 'axios'
import { get } from 'lodash'
import storage from './storage'
import router from '@/router'
import { baseURL } from '@/utils/baseURL'

/**
 * @description 创建请求实例
 */
function createService () {
  // 创建一个 axios 实例
  const service = axios.create()
  // 请求拦截
  service.interceptors.request.use(
    config => config,
    error => Promise.reject(error)
  )
  // 响应拦截
  service.interceptors.response.use(
    response => {
      if (response.status === 200) {
        return response.data
      } else {
        Message.error('数据获取失败')
      }
    },
    error => {
      const status = get(error, 'response.status')
      const data = get(error, 'response.data')
      if (status === 401) {
        router.replace('/Login')
        return Message.error('登录失效,请重新登录')
      }
      Message.error(data.message ? data.message : error.message)
    }
  )
  return service
}

/**
 * @description 创建请求方法
 * @param {Object} service axios 实例
 */
function createRequest (service) {
  return function (config) {
    const configDefault = {
      headers: {
        Qtoken: storage.get('token'),
        'Content-Type': get(config, 'headers.Content-Type', 'application/json'),
        _hotel: storage.get('hotelCode') || ''
      },
      timeout: 5000,
      baseURL: baseURL,
      data: {}
    }
    const option = Object.assign(configDefault, config)
    return service(option)
  }
}

// 网络请求的实例和请求方法
export const service = createService()
export const request = createRequest(service)

// src->api
import {request} from '../utils/service';

export default {
  // 登录
  login (data) {
    return request({
      url: '/api/Auth',
      method: 'post',
      data,
    })
  },
}

// 调用
import api from '../api/api'
async function getLogin(){
  let {data} = await api.login(data)
}
Last Updated:
Contributors: pengrengui