当前位置:   article > 正文

uniapp 简易通用的ajax 请求 封装 以及携带token去请求 (代码优化(新增请求日志和响应日志))_uniapp使用ajax

uniapp使用ajax

1、例如:在api文件夹中新建一个api.js

  1. // 公共的方法
  2. const baseUrl = "http://192.xxx.xx.xx:8889"; // 请求地址
  3. const $ajax = {
  4. get: function({
  5. url,
  6. param,
  7. header
  8. }) {
  9. return new Promise(function(resolve, reject) {
  10. uni.request({
  11. url: baseUrl + url,
  12. data: param,
  13. method: "GET",
  14. success: function(res) {
  15. if (res.statusCode !== 200) {
  16. reject(res);
  17. } else {
  18. resolve(res);
  19. }
  20. },
  21. fail: function(err) {
  22. reject(err);
  23. }
  24. })
  25. })
  26. },
  27. post: function({
  28. url,
  29. data,
  30. header
  31. }) {
  32. return new Promise(function(resolve, reject) {
  33. uni.request({
  34. url: baseUrl + url,
  35. data: data,
  36. method: "POST",
  37. header: {
  38. 'Content-Type': 'application/x-www-form-urlencoded'
  39. },
  40. success: function(res) {
  41. if (res.statusCode !== 200) {
  42. reject(res)
  43. } else {
  44. resolve(res);
  45. }
  46. },
  47. fail: function(err) {
  48. reject(err)
  49. }
  50. })
  51. })
  52. },
  53. postJSON: function({
  54. url,
  55. data,
  56. header
  57. }) {
  58. return new Promise(function(resolve, reject) {
  59. uni.request({
  60. url: baseUrl + url,
  61. data: data,
  62. method: "POST",
  63. header: {
  64. 'Content-Type': 'application/json;charset=UTF-8'
  65. },
  66. success: function(res) {
  67. if (res.statusCode !== 200) {
  68. reject(res)
  69. } else {
  70. resolve(res);
  71. }
  72. },
  73. fail: function(err) {
  74. reject(err)
  75. }
  76. })
  77. })
  78. },
  79. upImg: function({
  80. url,
  81. imgUrl
  82. }) {
  83. return new Promise(function(resolve, reject) {
  84. uni.uploadFile({
  85. url: "baseUrl" + url,
  86. filePath: imgUrl,
  87. name: 'file',
  88. success: function(uploadFileRes) {
  89. resolve(uploadFileRes);
  90. },
  91. fail: function(err) {
  92. reject(err)
  93. }
  94. });
  95. })
  96. }
  97. }
  98. export default $ajax;

2、引入

例如:在main.js中全局引入

  1. // 在main.js中引入
  2. import ajax from './api/api.js'

3、使用

  1. // get请求
  2. this.$ajax.get({
  3. url: `/wx/wxLogin`,
  4. param: {
  5. password: this.pwd,
  6. username: this.name,
  7. uuid: this.uuid
  8. }
  9. }).then((res) => {
  10. console.log(res.data)
  11. })

4、携带token

有的接口在发送http请求的时候需要验证token,登陆成功后我们需要把Authorization字段的值放到header里面,携带token去发送请求。

①在api文件夹中新建config.js文件,封装一下方法

  1. const app = {
  2. apiUrl: 'http://192.xxx.xx.xxx:8889', //请求的地址
  3. baseRequest(obj) {
  4. try {
  5. const userToken = uni.getStorageSync('userToken');
  6. if (userToken) {
  7. if (obj.header) {
  8. obj.header["Authorization"] = userToken;
  9. } else {
  10. obj.header = {
  11. "Authorization": userToken
  12. };
  13. }
  14. obj.url = this.apiUrl + obj.url;
  15. uni.request(obj)
  16. } else {
  17. console.log("获取不到userToken")
  18. }
  19. } catch (e) {
  20. console.log(e)
  21. console.log("获取不到userToken")
  22. }
  23. },
  24. }
  25. export default app

②登陆成功后设置缓存

  1. // 设置缓存
  2. uni.setStorageSync('userToken', res.data.token),

③其他地方调用

  1. // 顺便介绍一下获取缓存
  2. getToken() {
  3. uni.getStorage({
  4. key: 'userToken',
  5. success: (res) => {
  6. // console.log('这是获取key中的内容',res)
  7. this.tokenData = res.data;
  8. console.log('这是获取token', this.tokenData)
  9. if (this.tokenData) {
  10. }
  11. }
  12. })
  13. },
  1. // 注意要引入config.js
  2. import app from "@../../api/config.js"
  3. // 在methods中调用封装好的方法
  4. getMaintenance() {
  5. app.baseRequest({
  6. url: `/repairType/xxx/xxx`,
  7. method: 'get',
  8. success: (res) => {
  9. }
  10. })
  11. },

5. 请求代码优化(新增请求日志和响应日志)

  1. // interface.js
  2. const baseUrl = "https://xxxxxxxxxxx";
  3. export default {
  4. config: {
  5. baseUrl: baseUrl,
  6. header: {
  7. 'Content-Type':'application/json;charset=UTF-8',
  8. 'x-requested-with':"XMLHttpRequest"
  9. },
  10. data: {},
  11. method: "GET"|| "POST",
  12. dataType: "json", /* 如设为json,会对返回的数据做一次 JSON.parse */
  13. responseType: "text",
  14. success() {},
  15. fail() {},
  16. complete() {}
  17. },
  18. interceptor: {
  19. request: null,
  20. response: null
  21. },
  22. request(options) {
  23. /* console.log('options11')
  24. console.log(options) */
  25. if (!options) {
  26. options = {}
  27. }
  28. options.baseUrl = options.baseUrl || this.config.baseUrl
  29. options.dataType = options.dataType || this.config.dataType
  30. options.url = options.baseUrl + options.url
  31. options.data = options.data || {}
  32. options.method = options.method || this.config.method
  33. if(options.header){
  34. options.header['Content-Type'] = options.header['Content-Type']|| this.config.header['Content-Type']
  35. }
  36. return new Promise((resolve, reject) => {
  37. let _config = null
  38. options.complete = (response) => {
  39. let statusCode = response.statusCode
  40. response.config = _config
  41. if (process.env.NODE_ENV === 'development') {
  42. if (statusCode === 200) {
  43. /* console.log("【" + _config.requestId + "】 结果:" + JSON.stringify(response.data)) */
  44. }
  45. }
  46. if (this.interceptor.response) {
  47. let newResponse = this.interceptor.response(response)
  48. if (newResponse) {
  49. response = newResponse
  50. }
  51. }
  52. // 统一的响应日志记录
  53. _reslog(response)
  54. if (statusCode === 200) { //成功
  55. resolve(response);
  56. } else {
  57. reject(response)
  58. }
  59. }
  60. _config = Object.assign({}, this.config, options)
  61. _config.requestId = new Date().getTime()
  62. if (this.interceptor.request) {
  63. this.interceptor.request(_config)
  64. }
  65. // 统一的请求日志记录
  66. _reqlog(_config)
  67. if (process.env.NODE_ENV === 'development') {
  68. // console.log(_config)
  69. // console.log("【" + _config.requestId + "】 地址:" + _config.url)
  70. if (_config.data) {
  71. // console.log("【" + _config.requestId + "】 参数:" + JSON.stringify(_config.data))
  72. }
  73. }
  74. uni.request(_config);
  75. });
  76. },
  77. get(url, data, options) {
  78. if (!options) {
  79. options = {}
  80. }
  81. options.url = url
  82. options.data = data
  83. options.method = 'GET'
  84. return this.request(options)
  85. },
  86. post(url, data, options) {
  87. if (!options) {
  88. options = {}
  89. }
  90. options.url = url
  91. options.data = data
  92. options.method = 'POST'
  93. return this.request(options)
  94. },
  95. put(url, data, options) {
  96. if (!options) {
  97. options = {}
  98. }
  99. options.url = url
  100. options.data = data
  101. options.method = 'PUT'
  102. return this.request(options)
  103. },
  104. delete(url, data, options) {
  105. if (!options) {
  106. options = {}
  107. }
  108. options.url = url
  109. options.data = data
  110. options.method = 'DELETE'
  111. return this.request(options)
  112. }
  113. }
  114. /**
  115. * 请求接口日志记录
  116. */
  117. function _reqlog(req) {
  118. if (process.env.NODE_ENV === 'development') {
  119. console.log("【" + req.requestId + "】 地址:" + req.url)
  120. if (req.data) {
  121. console.log("【" + req.requestId + "】 请求参数:" + JSON.stringify(req.data))
  122. }
  123. }
  124. }
  125. /**
  126. * 响应接口日志记录
  127. */
  128. function _reslog(res) {
  129. let _statusCode = res.statusCode;
  130. if (process.env.NODE_ENV === 'development') {
  131. console.log("【" + res.config.requestId + "】 地址:" + res.config.url)
  132. if (res.config.data) {
  133. console.log("【" + res.config.requestId + "】 请求参数:" + JSON.stringify(res.config.data))
  134. }
  135. console.log("【" + res.config.requestId + "】 响应结果:" + JSON.stringify(res))
  136. }
  137. switch(_statusCode){
  138. case 200:
  139. break;
  140. case 401:
  141. break;
  142. case 404:
  143. break;
  144. default:
  145. break;
  146. }
  147. }

  1. // index.js
  2. import http from './interface'
  3. export const execute = (data = {}) => {
  4. if (data.url != 'logon') {
  5. //设置请求前拦截器
  6. http.interceptor.request = (config) => {
  7. let token = uni.getStorageSync('accessToken')
  8. delete config.header['Authorization']
  9. if (token) {
  10. config.header['Authorization'] = token
  11. }
  12. }
  13. //设置请求结束后拦截器
  14. http.interceptor.response = async (response) => {
  15. const statusCode = response.statusCode;
  16. if (response.header.authorization) {
  17. uni.setStorageSync('accessToken', response.header.authorization)
  18. }
  19. if (statusCode === 401) {
  20. uni.showToast({
  21. title: '登录已失效,请重新登录',
  22. icon: 'none',
  23. duration: 2000
  24. })
  25. setTimeout(() => {
  26. uni.navigateTo({
  27. url: "../../pages/login/login"
  28. });
  29. uni.removeStorageSync('accessToken');
  30. }, 2000)
  31. }
  32. return response;
  33. }
  34. return http.request(data)
  35. } else {
  36. return http.request(data)
  37. }
  38. }
  39. const interfaces = {
  40. }
  41. export default {
  42. execute,interfaces
  43. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/243022
推荐阅读
相关标签
  

闽ICP备14008679号