经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » HTML/CSS » HTML5 » 查看文章
uni-app开发经验分享十: 封装request请求
来源:cnblogs  作者:林恒  时间:2020/12/8 9:04:21  对本文有异议

http.js

//封装requset,uploadFile和downloadFile请求,新增get和post请求方法

  1. let http = {
  2. 'setBaseUrl': (url) => {
  3. if (url.charAt(url.length - 1) === "/") {
  4. url = url.substr(0, url.length - 1)
  5. }
  6. http.baseUrl = url;
  7. },
  8. 'header': {},
  9. 'beforeRequestFilter': (config) => { return config },
  10. 'beforeResponseFilter': (res) => { return res },
  11. 'afterResponseFilter': (successResult) => { },
  12. 'get': get,
  13. 'post': post,
  14. 'request': request,
  15. 'uploadFile': uploadFile,
  16. 'downloadFile': downloadFile
  17. }
  18. function init(con) {
  19. //url
  20. let url = http.baseUrl;
  21. if (url && con.url && !con.url.match(/^(http|https):\/\/([\w.]+\/?)\S*$/)) {
  22. if (con.url.charAt(0) !== "/") {
  23. con.url = "/" + con.url;
  24. }
  25. con.url = url.concat(con.url);
  26. }
  27. //header
  28. if (http.header != undefined && http.header != null) {
  29. if (!con.header) {
  30. con.header = http.header;
  31. } else {
  32. Object.keys(http.header).forEach(function (key) {
  33. con.header[key] = http.header[key]
  34. });
  35. }
  36. }
  37. }
  38. function request(con) {
  39. init(con);
  40. let config = {
  41. url: con.url ? con.url : http.baseUrl,
  42. data: con.data,
  43. header: con.header,
  44. method: con.method ? con.method : 'GET',
  45. dataType: con.dataType ? con.dataType : 'json',
  46. responseType: con.responseType ? con.responseType : 'text',
  47. success: con.success ? (res) => {
  48. http.afterResponseFilter(con.success(http.beforeResponseFilter(res)));
  49. } : null,
  50. fail: con.fail ? (res) => {
  51. con.fail(res);
  52. } : null,
  53. complete: con.complete ? (res) => {
  54. con.complete(res);
  55. } : null
  56. }
  57. return uni.request(http.beforeRequestFilter(config));
  58. }
  59. function get(url, con, success) {
  60. let conf = {};
  61. if (con && typeof con == 'function') {
  62. if (success && typeof success == 'object') {
  63. conf = success;
  64. }
  65. conf.success = con
  66. }else{
  67. if (con && typeof con == 'object') {
  68. conf = con;
  69. }
  70. conf.success = success;
  71. }
  72. if (url) {
  73. conf.url = url
  74. }
  75. conf.method = "GET";
  76. return request(conf);
  77. }
  78. function post(url, data, con, success) {
  79. let conf = {};
  80. if (con && typeof con == 'function') {
  81. if (success && typeof success == 'object') {
  82. conf = success
  83. }
  84. conf.success = con;
  85. } else {
  86. if (con && typeof con == 'object') {
  87. conf = con;
  88. }
  89. conf.success = success;
  90. }
  91. if (url) {
  92. conf.url = url
  93. }
  94. if (data) {
  95. conf.data = data
  96. }
  97. conf.method = "POST";
  98. return request(conf);
  99. }
  100. function uploadFile(con) {
  101. init(con);
  102. let config = {
  103. url: con.url ? con.url : http.baseUrl,
  104. files: con.files,
  105. filesType: con.filesType,
  106. filePath: con.filePath,
  107. name: con.name,
  108. header: con.header,
  109. formData: con.formData,
  110. success: con.success ? (res) => {
  111. http.afterResponseFilter(con.success(http.beforeResponseFilter(res)));
  112. } : null,
  113. fail: con.fail ? (res) => {
  114. con.fail(res);
  115. } : null,
  116. complete: con.complete ? (res) => {
  117. con.complete(res);
  118. } : null
  119. }
  120. return uni.uploadFile(http.beforeRequestFilter(config));
  121. }
  122. function downloadFile(con) {
  123. init(con);
  124. let config = {
  125. url: con.url ? con.url : http.baseUrl,
  126. header: con.header,
  127. success: con.success ? (res) => {
  128. http.afterResponseFilter(con.success(http.beforeResponseFilter(res)));
  129. } : null,
  130. fail: con.fail ? (res) => {
  131. con.fail(res);
  132. } : null,
  133. complete: con.complete ? (res) => {
  134. con.complete(res);
  135. } : null
  136. }
  137. return uni.downloadFile(http.beforeRequestFilter(config));
  138. }
  139. export default http

可以设置全局的url访问地址(会拼接请求的url成完整的url,所以在写url时只需要"/xxx"),也可以在请求时设置具体url(以http或https开头)

可以设置全局的header,如果请求时有header参数,会加上全局的header

可以设置拦截器,有发送请求前的拦截器beforeRequestFilter,参数是包含已经拼接完的url和header的请求参数,注意要返回;执行成功回调函数前的拦截器beforeResponseFilter,参数是回调成功函数的参数,注意要返回;执行成功回调函数后的拦截器afterResponseFilter,参数为成功回调函数的返回值。

具体例子

my.js

  1. import http from './http'
  2. const AUTH_TOKEN = "X-Auth-Token";
  3. http.setBaseUrl("http://localhost:8081");
  4. http.header['comp'] = "cjx913"
  5. if (uni.getStorageSync(AUTH_TOKEN)) {
  6. http.header[AUTH_TOKEN] = uni.getStorageSync(AUTH_TOKEN);
  7. }
  8. http.beforeResponseFilter = function (res) {
  9. //X-Auth-Token
  10. if (res.header) {
  11. var respXAuthToken = res.header[AUTH_TOKEN.toLocaleLowerCase()];
  12. if (respXAuthToken) {
  13. uni.setStorageSync(AUTH_TOKEN, respXAuthToken);
  14. http.header[AUTH_TOKEN] = respXAuthToken;
  15. }
  16. }
  17. return res;
  18. }
  19. let my = {
  20. 'http': http
  21. }
  22. export default my

main.js

  1. import Vue from 'vue'
  2. import App from './App'
  3. Vue.config.productionTip = true
  4. App.mpType = 'app'
  5. import fly from './fly/fly'
  6. Vue.prototype.$fly = fly
  7. import my from './my/my'
  8. var http = my.http;
  9. Vue.prototype.$http = http
  10. import store from './store'
  11. Vue.prototype.$store = store
  12. const app = new Vue({
  13. ...App
  14. })
  15. app.$mount()

index.js

  1. <script>
  2. export default {
  3. data() {
  4. return {
  5. title: 'Hello',
  6. name:'cjx913'
  7. }
  8. },
  9. onLoad() {
  10. },
  11. methods: {
  12. session:function(){
  13. // this.$fly.get('/session')
  14. // .then(function (response) {
  15. // console.log("hello");
  16. // console.log(response.data);
  17. // console.log(response);
  18. // })
  19. // .catch(function (error) {
  20. // console.log(error);
  21. // });
  22. // this.$http.request({
  23. // url:"session",
  24. // success:(res)=>{
  25. // console.log(res);
  26. // }
  27. // })
  28. // this.$http.get("/session",function(res){
  29. // console.log(res);
  30. // }
  31. // )
  32. this.$http.get("/session",{
  33. success:function(res){
  34. console.log(res);
  35. }
  36. }
  37. )
  38. }
  39. }
  40. }
  41. </script>

上述是简单设置baseUrl,header和通过拦截器拦截response的X-Auth-Token,并让请求带上X-Auth-Token

原文链接:http://www.cnblogs.com/smileZAZ/p/14086835.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号