request.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import sysconfig from '../sysconfig/sysconfig.js'
  2. import crypt from './crypt.js'
  3. let Fly = require("flyio/dist/npm/wx")//引入fly包
  4. let fly = new Fly()
  5. //本地
  6. fly.config.baseURL = "http://127.0.0.1:8080/msapi"
  7. //远程
  8. fly.config.baseURL = "http://www.locaty.com.cn/msapi"
  9. //请求拦截,config是请求对象
  10. fly.interceptors.request.use((config) => {
  11. //组织请求参数密钥
  12. const aesKey = sysconfig.copyright + sysconfig.app.snCode
  13. //同步读取本地token
  14. const token = wx.getStorageSync(sysconfig.user.tokenKey)
  15. if (token) {
  16. //判断当前请求api是否在白名单内,在白名单内的api不需要添加token
  17. let apiName = ""
  18. const urlList = config.url.split("/")
  19. const apiWhiteList = sysconfig.apiWhiteList
  20. if (urlList.length > 1) {
  21. apiName = urlList[1]
  22. } else {
  23. apiName = urlList[0]
  24. }
  25. //不在白名单内,则添加token,并且对token进行加密
  26. if (!apiWhiteList.includes(apiName)) {
  27. let item = {}
  28. item["rnd"] = Math.random().toString()
  29. item["token"] = token
  30. let plaintext = JSON.stringify(item)
  31. //对token进行加密
  32. const ciphertext = crypt.aesEncode(plaintext, aesKey)
  33. config.headers.Authorization = ciphertext
  34. }
  35. }
  36. //对get参数进行加密
  37. if (config.params && (Object.keys(config.params).length) > 0) {
  38. const params = config.params
  39. const paramsText = JSON.stringify(params)
  40. if (paramsText != "{}") {
  41. const ciphertext = crypt.aesEncode(params, aesKey)
  42. config.params = {}
  43. config.params = ciphertext
  44. }
  45. }
  46. //对post参数进行加密
  47. if (config.body && (Object.keys(config.body).length) > 0) {
  48. const plaintext = JSON.stringify(config.body)
  49. const ciphertext = crypt.aesEncode(plaintext, aesKey)
  50. config.body = {}
  51. config.body = ciphertext
  52. }
  53. return config
  54. }, error => {
  55. return Promise.reject(error)
  56. })
  57. export default fly