index.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // 根域名
  2. var baseUrl = 'http://121.28.24.104:13898/app/';
  3. // var baseUrl = 'http://192.168.1.59:8080';
  4. module.exports = (vm) => {
  5. // 初始化请求配置:config 为默认全局配置
  6. uni.$u.http.setConfig((config) => {
  7. config.baseURL = baseUrl; /* 根域名 */
  8. // 配置请求头信息
  9. config.header = {
  10. // 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
  11. // 'content-type': 'application/json;charset=utf-8',
  12. };
  13. config.method = 'GET'; //支持post、get、put、delete
  14. config.dataType = 'json'; // 设置为json,返回后会对数据进行一次JSON.parse()
  15. config.timeout = 60000;
  16. return config
  17. })
  18. // 请求拦截
  19. uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
  20. // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
  21. config.data = config.data || {};
  22. config.header['content-Type']=config.header['content-Type']==undefined?'application/json;charset=utf-8':config.header['content-Type']
  23. // 设置token
  24. // const token = getApp().globalData.token || '';
  25. const token = uni.getStorageSync('token') || '';
  26. config.header['Authorization'] ='Bearer ' + token
  27. // 设置设备端类型
  28. // config.header['os'] = uni.$u.os() || '';
  29. return config;
  30. }, config => { // 可使用async await 做异步操作
  31. return Promise.reject(config)
  32. })
  33. // 响应拦截
  34. uni.$u.http.interceptors.response.use((response) => {
  35. /* 对响应成功做点什么 可使用async await 做异步操作*/
  36. const res = response.data;
  37. // console.log(res)`
  38. // res为服务端返回值,可能有code,result等字段
  39. if (res.code == 200) {
  40. return res;
  41. } else if (res.code == 400) {
  42. uni.$u.toast(res.msg)
  43. return false;
  44. } else if (res.code == 401) {
  45. // 401为token失效
  46. // uni.setStorageSync('token', ''); // 缓存token
  47. uni.$u.toast(res.msg)
  48. // setTimeout(() => {
  49. // vm.$u.route('/pages/login/login')
  50. uni.clearStorageSync()
  51. uni.reLaunch({
  52. url:"/pages/login/login"
  53. })
  54. // }, 1500)
  55. return false;
  56. } else if (res.code == 405) {
  57. // 405为token为空
  58. return false;
  59. } else if (res.code == 1) {
  60. uni.$u.toast(res.msg)
  61. return false;
  62. } else if (res.code == undefined) {
  63. return res;
  64. } else {
  65. // 如果需要catch返回,则进行reject
  66. return Promise.reject(res)
  67. }
  68. }, (response) => {
  69. // 对响应错误做点什么 (statusCode !== 200)
  70. uni.showToast({
  71. title:"网络异常,请稍后重试",
  72. icon:"none"
  73. })
  74. return Promise.reject(response)
  75. })
  76. }