request.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * 文档地址:https://uiadmin.net/uview-plus/js/http.html
  3. */
  4. const baseUrl = "https://bk.shuhi.com";
  5. export function initRequest() {
  6. console.log("初始化了 http 请求代码");
  7. // 初始化请求配置
  8. uni.$u.http.setConfig((config) => {
  9. /* config 为默认全局配置*/
  10. // config.baseURL = `http://192.168.1.2:8080`; /* 根域名 */
  11. config.baseURL = baseUrl; /* 根域名 */
  12. config.custom.toast = true; // 默认消息有msg会显示出来
  13. config.sslVerify = false; // 忽略 SSL 证书验证
  14. return config;
  15. });
  16. // 请求拦截
  17. uni.$u.http.interceptors.request.use(
  18. (config) => {
  19. // 可使用async await 做异步操作
  20. // console.log('请求拦截', config)
  21. // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
  22. config.data = config.data || {};
  23. // 挂载 token
  24. let token = uni.getStorageSync("token");
  25. config.header.Authorization = token ? `Bearer ${token}` : "";
  26. return config;
  27. },
  28. (config) => {
  29. // 可使用async await 做异步操作
  30. return Promise.reject(config);
  31. }
  32. );
  33. // 响应拦截
  34. uni.$u.http.interceptors.response.use(
  35. (response) => {
  36. /* 对响应成功做点什么 可使用async await 做异步操作*/
  37. // console.log('响应拦截', response)
  38. const data = response.data;
  39. // 自定义参数
  40. const custom = response.config?.custom;
  41. if (data.code !== 200) {
  42. // 身份认证失败,需要重新登录
  43. if (data.code === 401) {
  44. uni.$u.toast(data.msg || "身份认证失败,请先登录");
  45. uni.removeStorageSync("token");
  46. setTimeout(() => {
  47. uni.$u.route({
  48. type: "reLaunch",
  49. url: "/pages/login/login", // 跳转到登录页
  50. });
  51. }, 1000);
  52. } else {
  53. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  54. if (custom.toast !== false) {
  55. uni.$u.toast(data.msg);
  56. }
  57. // 如果需要catch返回,则进行reject
  58. // if (custom?.catch) {
  59. // return Promise.reject(data)
  60. // } else {
  61. // // 否则返回一个pending中的promise,请求不会进入catch中
  62. // return new Promise(() => { })
  63. // }
  64. return data;
  65. }
  66. }
  67. // return data.data === undefined ? {} : data.data
  68. return data; // 这里视不同的后端返回数据格式而定
  69. },
  70. (response) => {
  71. // 对响应错误做点什么 (statusCode !== 200)
  72. return Promise.reject(response);
  73. }
  74. );
  75. }
  76. export default baseUrl;