http.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import store from './store'
  2. const baseUrl = process.env.NODE_ENV === 'development' ? "http://192.168.1.101:8000":"http://sxzg.ngrok.ssly.site";
  3. const baseApiUrl = baseUrl + "/api";
  4. function initPramas() {
  5. arguments[0].url = baseApiUrl + arguments[0].url;
  6. arguments[0].timeout = 10000
  7. // console.log(typeof arguments[0].fail)
  8. const fail = arguments[0].fail
  9. arguments[0].fail = (res) => {
  10. console.log(res)
  11. let msg = '请求失败'
  12. if (res.data && res.data.msg) {
  13. msg = res.data.msg
  14. }
  15. uni.showToast({
  16. title: msg,
  17. icon: "none"
  18. })
  19. fail(res)
  20. }
  21. const success = arguments[0].success
  22. arguments[0].success = (res) => {
  23. console.log(res)
  24. if (typeof res.data === "string") {
  25. try {
  26. res.data = JSON.parse(res.data)
  27. } catch (err) {}
  28. }
  29. if (res.data.code === 0) {
  30. uni.showToast({
  31. title: res.data.msg,
  32. icon: "none"
  33. })
  34. arguments[0].fail(res)
  35. }
  36. if (res.data.code === 1) {
  37. success(res)
  38. }
  39. if (res.data.code === 401 || res.statusCode === 401) {
  40. uni.navigateTo({
  41. url: "/pages/user/login"
  42. })
  43. }
  44. }
  45. if (typeof arguments[0].header === "undefined") {
  46. arguments[0].header = {}
  47. }
  48. if (store.state.user.token) {
  49. arguments[0].header["token"] = store.state.user.token;
  50. }
  51. return arguments[0];
  52. }
  53. export default {
  54. baseUrl: baseUrl,
  55. get: function() {
  56. let obj = initPramas(arguments[0]);
  57. obj.method = "GET";
  58. uni.request(obj);
  59. },
  60. post: function() {
  61. let obj = initPramas(arguments[0]);
  62. obj.method = "POST";
  63. obj.header["Content-type"] = "application/x-www-form-urlencoded"
  64. console.log(obj);
  65. uni.request(obj);
  66. },
  67. upload: function() {
  68. let obj = initPramas(arguments[0]);
  69. obj.url = baseApiUrl + '/common/upload';
  70. uni.uploadFile(obj)
  71. }
  72. }