http.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { API_BASE_URL } from './util'
  2. const BASE_URL = `${API_BASE_URL}`;
  3. function request(url: String, options: any) {
  4. return new Promise((resolve, reject) => {
  5. let token = wx.getStorageSync('token')
  6. wx.request(Object.assign({
  7. url: url.indexOf('://') == -1 ? BASE_URL + url : url,
  8. method: options.method,
  9. data: options.data,
  10. header: Object.assign({ token: token }, options.header),
  11. success(res: any) {
  12. if (res.data.code == 0 || res.data.code == 200 || res.data.errno === 0) {
  13. resolve(res.data)
  14. } else {
  15. reject(res)
  16. }
  17. },
  18. fail(err: any) {
  19. console.log(err, '请求失败')
  20. reject(err)
  21. }
  22. }, options))
  23. setTimeout(() => reject('time out'), 5000)
  24. })
  25. }
  26. function get(url: String, data: any, options: any = {}) {
  27. options.method = 'GET'
  28. options.data = data
  29. return request(url, options)
  30. }
  31. function post(url: String, data: any = {}, options: any = {}) {
  32. options.method = 'POST'
  33. options.data = Object.assign({}, data)
  34. return request(url, options)
  35. }
  36. export default {
  37. request,
  38. get,
  39. post
  40. }