http.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import store from './store'
  2. const baseUrl = "http://192.168.1.101:8000";
  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. if (typeof arguments[0].fail === "undefined") {
  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. }
  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. }