import axios from 'axios'

axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.interceptors.request.use((config) => {
  let token = sessionStorage.getItem('token')
  if (token) {
    config.headers['token'] = token
  } else {
    config.headers['token'] = ''
  }
  if (window.xtoken) {
    config.headers['x'] = window.xtoken
  }
  return config
}, (error) => {
  if (error) {
    console.log('axios.interceptors.request', error)
  }
  const err = {
    data: {
      code: 400,
      msg: '错误的传参!'
    }
  }
  return Promise.reject(err)
})

axios.interceptors.response.use((res) => {
  if (Number(res.data.code) !== 200) {
    return Promise.resolve(res)
  }
  return res
}, (error) => {
  if (error && error.response) {
    console.log('axios.interceptors.response', error)
  }
  console.log(error)
  const err = {
    data: {
      code: 404,
      msg: '网络有点慢,换个姿势再来一次!'
    }
  }
  return Promise.reject(err)
})

export default axios
