request.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import ERROR_CODE from '../../config/error_code'
  2. import { API_BASE_URL } from './../../config/config'
  3. import { loginByUserInfo } from '../../utils/login'
  4. const BASE_URL = `${API_BASE_URL}/app/`
  5. // 需要登录的错误码
  6. const needLoginErrorCode = [3004, 3005, 3006, 3013]
  7. Promise.prototype.finally = function (callback) {
  8. var Promise = this.constructor;
  9. return this.then(
  10. function (value) {
  11. Promise.resolve(callback()).then(
  12. function () {
  13. return value;
  14. }
  15. );
  16. },
  17. function (reason) {
  18. Promise.resolve(callback()).then(
  19. function () {
  20. throw reason;
  21. }
  22. );
  23. }
  24. );
  25. }
  26. function request (url, options) {
  27. return new Promise((resolve, reject) => {
  28. wx.request(Object.assign({
  29. url: url.indexOf('://') === -1 ? BASE_URL + url : url,
  30. method: options.method,
  31. data: options.data,
  32. // header: {
  33. // token: app.globalData.token
  34. // },
  35. success (res) {
  36. console.log(res, url.indexOf('://') === -1 ? BASE_URL + url : url, '接口返回')
  37. if (res.data.code == 0 || res.data.code == 200) {
  38. resolve(res.data)
  39. } else if (needLoginErrorCode.indexOf(Number(res.data.code)) !== -1) {
  40. wx.navigateTo({
  41. url: `/pages/login/login`
  42. })
  43. } else {
  44. reject(res)
  45. }
  46. },
  47. fail (err) {
  48. reject(err)
  49. }
  50. }, options))
  51. setTimeout(() => reject('time out'), 5000)
  52. })
  53. }
  54. function get (url, data, options = {}) {
  55. options.method = 'GET'
  56. options.data = data
  57. return request(url, options)
  58. }
  59. function post (url, data = {}, options = {}) {
  60. options.method = 'POST'
  61. // token和user_ID放在url上, 后续后端再做优化
  62. const app = getApp();
  63. url += `?token=${app.globalData.token || ''}&user_id=${app.globalData.userinfo.user_id}`
  64. options.data = Object.assign({
  65. user_id: app.globalData.userinfo.user_id
  66. }, data)
  67. return request(url, options)
  68. }
  69. export default {
  70. request,
  71. get,
  72. post
  73. }