项目中接口的配置,request.js中的总接口配置以及api内的文件配置等

首先要安装axios

npm install axios --save

pc端的配置(以往的项目,较复杂)

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
let host = "";

if (process.env.NODE_ENV === 'development') {	//连接的服务器
  // host = 'http://192.168.3.95:8088';
  host = "http://121.196.184.146:8088"; //线上
  // host = 'http://192.168.3.93:8088';
  // host = 'http://192.168.3.110:8088';
} else {
  host = "http://121.196.184.146:8088";
}

const request = axios.create({	//axios异步请求
  baseURL: host, // url = base url + request url
  timeout: 30000 // request timeout
})
// request interceptor
request.interceptors.request.use(	//请求钱拦截器
  config => {
    if (store.getters.token) {
      config.headers['Auth-Token'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
request.interceptors.response.use(	//请求后拦截器
  response => {
    const res = response;

    if (res.status == 200 && res.data.result_code == -101) {
      Message({
        message: '网络连接失败,请重新登录',
        type: 'error',
        duration: 1800
      });
      setTimeout(function () {
        window.sessionStorage.clear();
        window.localStorage.clear();
        window.location.href = "/"
      }, 2000);
      return;
    }
    if (response.status == 200) {
      return Promise.resolve(response);
    }

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 1800
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export {
  request,
  host
}

移动端的配置(较简单)

import axios from "axios";

let host = ''

if (process.env.NODE_ENV === 'development') {
    host = "http://121.196.184.146:8089";
    // host = "http://192.168.3.148:8088"; //闫
    // host = "http://192.168.3.58:8088";  //磊
    // host = "http://192.168.3.246:8088"; //许 } else {
    host = "http://121.196.184.146:8088"; }

window.$host = host || ''

const serve = axios.create({
    baseURL: host,
    timeout: 300000, });

serve.interceptors.request.use(config => {
    if (localStorage.token) {
        config.headers['Auth-Token'] = localStorage.token
    }
    return config; }, error => {
    return error; });

export default serve

其次在api文件夹中建一个all.js所有的请求类型

import request from '@/utils/request'
import { Toast, Dialog } from 'vant';	//vant框架

function handle(res) {
  if (res && res.data) {
    if (res.data.result_code == -101) {
      Dialog.alert({
        title: '提示',
        message: '授权失效,请重新登录',
      }).then(() => {
        window.localStorage.clear()
        window.sessionStorage.clear()
        window.location.href = '/'
      })
      return
    }
    if (![0, 1, 2].includes(res.data.result_code)) {
      Toast({
        message: res.data.err_msg || '服务异常',
        position: 'bottom',
      })
      return handleErr(res.data)
    }
    return Promise.resolve(res.data)
  }
}

function handleErr(err) {
  return Promise.reject(err)
}

function handleDL(res) {
  let bytes = res.data
  let cType = res.headers["content-type"]
  const blob = new Blob([bytes], { type: cType })
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  document.body.appendChild(a)
  a.href = url
  a.click()
  a.remove()
  window.URL.revokeObjectURL(url)
}

const http = {
  post(url) {
    return (params, href = '') => request.post(url + href, params).then(res => {
      return handle(res)
    }).catch(err => {
      return handleErr(err)
    })
  },
  form(url) {
    return (params) => request({ url: url, method: 'post', params }).then(res => {
      return handle(res)
    }).catch(err => {
      return handleErr(err)
    })
  },
  get(url) {
    return (params) => request.get(url, { params }).then(res => {
      return handle(res)
    }).catch(err => {
      return handleErr(err)
    })
  },
  file(url) {
    return (params) => request.post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res => {
      return handle(res)
    }).catch(err => {
      return handleErr(err)
    })
  },
  download(url) {
    return (params) => request.post(url, params, {
      responseType: 'blob'
    }).then(res => {
      handleDL(res)
    }).catch(err => {
      return handleErr(err)
    })
  }
}

export default http

然后在api文件夹中建立接口的文件

import http from './all.js';

const allPort = {
	//写接口,例:
	openAccount_addMember: http.post('/ysh/member/addMember')
}

export default allPort

在api文件夹中的index.js内

import allPort from './port.js';

export default {
  ...allPort
}

最后还需要在main.js中将文件引入

import api from './api';  //全局接口

项目中的运用

this.$api.setting_receiveMessage({messageSwitch:messageSwitch}).then(res => {
	console.log(res)
})
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值