RequestUtils.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { extend } from 'umi-request'
  2. import qs from 'qs'
  3. import { getAsyncStorage } from './AsyncStorageUtils'
  4. const baseUrl = 'http://dingdong.izouma.com'
  5. const request = extend({
  6. prefix: baseUrl,
  7. credentials: 'include',
  8. errorHandler: (error) => {
  9. let errorInfo = ''
  10. if (error.response) {
  11. errorInfo = error.data
  12. } else {
  13. errorInfo = error.message
  14. }
  15. throw errorInfo
  16. },
  17. })
  18. request.interceptors.request.use(
  19. (url, options) => {
  20. if (options.requestType === 'form') {
  21. options.headers = {
  22. Accept: 'application/json',
  23. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  24. ...options.headers,
  25. }
  26. options.data = qs.stringify(options.data)
  27. }
  28. return getAsyncStorage('token').then((token) => {
  29. const headers = {
  30. 'Access-Control-Allow-Origin': '*',
  31. ...options.headers,
  32. }
  33. if (token) {
  34. headers.Authorization = `Bearer ${token}`
  35. }
  36. return Promise.resolve({
  37. url,
  38. options: {
  39. ...options,
  40. headers,
  41. },
  42. })
  43. })
  44. },
  45. { global: true }
  46. )
  47. export default request