network.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import store from '../store'
  2. import { env } from '../static/config'
  3. export function requestApi (reqUrl, type = 'POST', data = {}, auth = '', multipart = false, arraybuffer = false) {
  4. if (!reqUrl) { return }
  5. let headers = {}
  6. if (auth === 'member') {
  7. headers['X-DS-KEY'] = store.state.member.token
  8. }
  9. type = type.toUpperCase()
  10. reqUrl = env.API_HOST + reqUrl
  11. return new Promise((resolve, reject) => {
  12. function returnData(res) {
  13. console.log('res==>>',res)
  14. if(arraybuffer){
  15. resolve(res.data)
  16. }else{
  17. if (res.data.code === 10000) {
  18. resolve(res.data)
  19. } else if (res.data.code === 11001) {
  20. var pages = getCurrentPages()
  21. var page = pages[pages.length - 2]
  22. if (page && (page.route.search('pages/member') != -1)) {
  23. }else{
  24. uni.navigateTo({
  25. url: '/pages/home/memberlogin/Login?clear=1'
  26. }) // token过期,需要删除
  27. }
  28. } else {
  29. reject(res.data)
  30. }
  31. }
  32. }
  33. if (multipart) {
  34. var filePath = data.filePath
  35. var name = data.name
  36. delete data.filePath
  37. uni.uploadFile({
  38. url: reqUrl,
  39. filePath: filePath,
  40. name: name,
  41. formData: data,
  42. header: headers,
  43. success: (res) => {
  44. res.data = JSON.parse(res.data)
  45. returnData(res)
  46. },
  47. fail: (error) => {
  48. reject(error)
  49. }
  50. })
  51. } else {
  52. uni.request({
  53. url: reqUrl,
  54. data: data,
  55. header: headers,
  56. method: type,
  57. withCredentials: true,
  58. responseType:arraybuffer?'arraybuffer':'text',
  59. success: (res) => {
  60. returnData(res)
  61. },
  62. fail: (error) => {
  63. reject(error)
  64. },
  65. })
  66. }
  67. })
  68. }
  69. export function requestRaw(reqUrl, type = 'POST', data = {}) {
  70. type = type.toUpperCase()
  71. return new Promise((resolve, reject) => {
  72. uni.request({
  73. url: reqUrl,
  74. data: data,
  75. method: type,
  76. withCredentials: true,
  77. success: (res) => {
  78. resolve(res.data)
  79. },
  80. fail: (error) => {
  81. reject(error)
  82. }
  83. })
  84. })
  85. }