1. const baseUrl = 'https://api.it120.cc';
    2. const http = ({ url = '', param = {}, ...other } = {}) => {
    3. wx.showLoading({
    4. title: '请求中,请耐心等待..'
    5. });
    6. let timeStart = Date.now();
    7. return new Promise((resolve, reject) => {
    8. wx.request({
    9. url: getUrl(url),
    10. data: param,
    11. header: {
    12. 'content-type': 'application/json' // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded"
    13. },
    14. ...other,
    15. complete: (res) => {
    16. wx.hideLoading();
    17. console.log(`耗时${Date.now() - timeStart}`);
    18. if (res.statusCode >= 200 && res.statusCode < 300) {
    19. resolve(res.data)
    20. } else {
    21. reject(res)
    22. }
    23. }
    24. })
    25. })
    26. }
    27. const getUrl = (url) => {
    28. if (url.indexOf('://') == -1) {
    29. url = baseUrl + url;
    30. }
    31. return url
    32. }
    33. // get方法
    34. const _get = (url, param = {}) => {
    35. return http({
    36. url,
    37. param
    38. })
    39. }
    40. const _post = (url, param = {}) => {
    41. return http({
    42. url,
    43. param,
    44. method: 'post'
    45. })
    46. }
    47. const _put = (url, param = {}) => {
    48. return http({
    49. url,
    50. param,
    51. method: 'put'
    52. })
    53. }
    54. const _delete = (url, param = {}) => {
    55. return http({
    56. url,
    57. param,
    58. method: 'put'
    59. })
    60. }
    61. module.exports = {
    62. baseUrl,
    63. _get,
    64. _post,
    65. _put,
    66. _delete
    67. }

    使用:

    1. const api = require('../../utils/api.js')
    2. // 单个请求
    3. api.get('list').then(res => {
    4. console.log(res)
    5. }).catch(e => {
    6. console.log(e)
    7. })
    8. // 一个页面多个请求
    9. Promise.all([
    10. api.get('list'),
    11. api.get(`detail/${id}`)
    12. ]).then(result => {
    13. console.log(result)
    14. }).catch(e => {
    15. console.log(e)
    16. })