http.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. let baseUrl = ''
  2. if (process.env.NODE_ENV === 'development') {
  3. baseUrl = 'http://anvideo.nxmy.com:8011';
  4. } else {
  5. baseUrl = 'http://anvideo.nxmy.com:8011';
  6. }
  7. function service(options = {}) {
  8. uni.showLoading({
  9. title: '加载中'
  10. });
  11. options.url = `${baseUrl}${options.url}`;
  12. // 判断本地是否存在token,如果存在则带上请求头
  13. let token = uni.getStorageSync('token')
  14. options.header = {
  15. 'content-type': 'application/json',
  16. 'Authorization': `Bearer ${token || false}` // 这里是token(可自行修改)
  17. };
  18. // resolved是返回成功数据,rejected返回错误数据
  19. return new Promise((resolved, rejected) => {
  20. options.success = (res) => {
  21. // 如果请求回来的状态码不是200则执行以下操作
  22. uni.hideLoading();
  23. if (res.statusCode === 404 || res.statusCode === 500) {
  24. uni.showToast({
  25. icon: 'none',
  26. duration: 3000,
  27. title: '服务器错误,请稍后再试'
  28. });
  29. rejected()
  30. } else {
  31. resolved(res)
  32. }
  33. // if (res.data.code !== 200) {
  34. // uni.showToast({
  35. // icon: 'none',
  36. // duration: 3000,
  37. // title: `${res.data.msg}`
  38. // });
  39. // rejected(res)
  40. // } else {
  41. // resolved(res.data.data)
  42. // }
  43. };
  44. options.fail = (err) => {
  45. uni.hideLoading();
  46. uni.showToast({
  47. icon: 'none',
  48. duration: 3000,
  49. title: '服务器错误,请稍后再试'
  50. });
  51. rejected(err);
  52. };
  53. uni.request(options);
  54. });
  55. }
  56. export default service;