业务交流通
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

request.js 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // wx.request封装
  2. const app = getApp()
  3. const request = async (url, options, contentType) => {
  4. let openId;
  5. await new Promise(resolve => {
  6. let tiems = setInterval(() => {
  7. // 如果此时openid已被赋值
  8. openId = app.globalData.openid; // data里要固定添加openid(项目需要)
  9. if (!!app.globalData.openid) {
  10. clearInterval(tiems)
  11. resolve()
  12. }
  13. }, 500);
  14. })
  15. !!contentType?contentType:contentType="application/json"
  16. return new Promise( (resolve, reject) => {
  17. wx.request({
  18. url: `${app.mangerUrl}${url}?openId=${openId}`,//获取域名接口地址
  19. method: options.method, //配置method方法
  20. data:options.data,
  21. //如果是GET,GET自动让数据成为query String,其他方法需要让options.data转化为字符串
  22. header: {
  23. 'Content-Type': contentType,
  24. 'Cookie':wx.getStorageSync('cookieKey')||''
  25. },
  26. success(request) {
  27. if (request && request.header && request.header['Set-Cookie']) {
  28. if(request.header['Set-Cookie'].indexOf("SESSION")==0){
  29. wx.setStorageSync('cookieKey', request.header['Set-Cookie']); //保存Cookie到Storage
  30. }
  31. }
  32. //监听成功后的操作
  33. resolve(request.data)
  34. },
  35. fail(error) {
  36. //返回失败也同样传入reject()方法
  37. reject(error.data)
  38. }
  39. })
  40. })
  41. }
  42. //封装get方法
  43. const get = (url, options = {}) => {
  44. return request(url, {
  45. method: 'GET',
  46. data: options
  47. })
  48. }
  49. //封装post方法
  50. const post = (url, options,contentType) => {
  51. return request(url, {
  52. method: 'POST',
  53. data: options
  54. },contentType)
  55. }
  56. //封装put方法
  57. const put = (url, options) => {
  58. return request(url, {
  59. method: 'PUT',
  60. data: options
  61. })
  62. }
  63. //封装remove方法
  64. // 不能声明DELETE(关键字)
  65. const remove = (url, options) => {
  66. return request(url, {
  67. method: 'DELETE',
  68. data: options
  69. })
  70. }
  71. //抛出wx.request的post,get,put,remove方法
  72. module.exports = {
  73. get,
  74. post,
  75. put,
  76. remove
  77. }