request.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import Request from '@/js_sdk/luch-request/luch-request/index.js'
  2. import cfg from '@/config.js'
  3. const http = new Request()
  4. http.interceptors.request.use(
  5. (config) => {
  6. // 可使用async await 做异步操作
  7. // config.header = {
  8. // ...config.header,
  9. // a: 1 // 演示拦截器header加参
  10. // }
  11. // 演示custom 用处
  12. // if (config.custom.auth) {
  13. // config.header.token = 'token'
  14. // }
  15. config.header['Authorization'] =
  16. 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX3R5cGUiOiIwMCIsInVzZXJfaWQiOjEsImxvZ2luX3R5cGUiOiJMaW5rV2VDaGF0QVBJIiwidXNlcl9uYW1lIjoiYWRtaW4iLCJ1c2VyX2tleSI6IjYyZjRiYWZmLWY2NzYtNGNlOS1iNDNhLTZhMjhlM2QwYTEwNiIsImNvcnBfbmFtZSI6IuS7n-W-ruenkeaKgCIsImNvcnBfaWQiOiJ3dzYyMmZjODUyZjc5YzNmMTMifQ.CvkoSw7K1eT-AjmfFYX5e2MlxKFNjfqzPpIwPlEuNDRL3ZASTW7t6UlGUl5CbYGI-F-3EPcVvFm9PcEk_YKtlQ'
  17. // if (config.custom.loading) {
  18. // uni.showLoading()
  19. // }
  20. /**
  21. /* 演示
  22. if (!token) { // 如果token不存在,return Promise.reject(config) 会取消本次请求
  23. return Promise.reject(config)
  24. }
  25. **/
  26. return config
  27. },
  28. (config) => {
  29. // 可使用async await 做异步操作
  30. return Promise.reject(config)
  31. },
  32. )
  33. http.interceptors.response.use(
  34. (response) => {
  35. /* 对响应成功做点什么 可使用async await 做异步操作*/
  36. let data = response.data
  37. if (data.code == 200) {
  38. return data
  39. }
  40. uni.hideLoading()
  41. uni.showToast({
  42. icon: 'none',
  43. title: data.msg,
  44. duration: 3000,
  45. })
  46. return Promise.reject(response) // return Promise.reject 可使promise状态进入catch
  47. },
  48. (response) => {
  49. /* 对响应错误做点什么 (statusCode !== 200)*/
  50. console.log(response)
  51. return Promise.reject(response)
  52. },
  53. )
  54. export async function post(url, data) {
  55. return http.request({
  56. method: 'POST', // 请求方法必须大写
  57. url,
  58. data,
  59. })
  60. }
  61. export async function get(url, params) {
  62. return http.get(url, {
  63. params,
  64. })
  65. }
  66. export default function(config = {}) {
  67. config.baseURL = cfg.BASE_API
  68. // 兼容get方法使用data传参
  69. if ((config.method || 'get').toLowerCase() === 'get' && !config.params) {
  70. config.params = config.data
  71. }
  72. return http.request(config)
  73. }