Procházet zdrojové kódy

fix[utils]: param2Obj bug when url params includes ==

花裤衩 před 4 roky
rodič
revize
8865514c81
3 změnil soubory, kde provedl 46 přidání a 21 odebrání
  1. 13 11
      mock/utils.js
  2. 12 10
      src/utils/index.js
  3. 21 0
      tests/unit/utils/param2Obj.spec.js

+ 13 - 11
mock/utils.js

@@ -2,20 +2,22 @@
2 2
  * @param {string} url
3 3
  * @returns {Object}
4 4
  */
5
-function param2Obj(url) {
6
-  const search = url.split('?')[1]
5
+export function param2Obj(url) {
6
+  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
7 7
   if (!search) {
8 8
     return {}
9 9
   }
10
-  return JSON.parse(
11
-    '{"' +
12
-      decodeURIComponent(search)
13
-        .replace(/"/g, '\\"')
14
-        .replace(/&/g, '","')
15
-        .replace(/=/g, '":"')
16
-        .replace(/\+/g, ' ') +
17
-      '"}'
18
-  )
10
+  const obj = {}
11
+  const searchArr = search.split('&')
12
+  searchArr.forEach(v => {
13
+    const index = v.indexOf('=')
14
+    if (index !== -1) {
15
+      const name = v.substring(0, index)
16
+      const val = v.substring(index + 1, v.length)
17
+      obj[name] = val
18
+    }
19
+  })
20
+  return obj
19 21
 }
20 22
 
21 23
 module.exports = {

+ 12 - 10
src/utils/index.js

@@ -99,17 +99,19 @@ export function formatTime(time, option) {
99 99
  * @returns {Object}
100 100
  */
101 101
 export function param2Obj(url) {
102
-  const search = url.split('?')[1]
102
+  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
103 103
   if (!search) {
104 104
     return {}
105 105
   }
106
-  return JSON.parse(
107
-    '{"' +
108
-      decodeURIComponent(search)
109
-        .replace(/"/g, '\\"')
110
-        .replace(/&/g, '","')
111
-        .replace(/=/g, '":"')
112
-        .replace(/\+/g, ' ') +
113
-      '"}'
114
-  )
106
+  const obj = {}
107
+  const searchArr = search.split('&')
108
+  searchArr.forEach(v => {
109
+    const index = v.indexOf('=')
110
+    if (index !== -1) {
111
+      const name = v.substring(0, index)
112
+      const val = v.substring(index + 1, v.length)
113
+      obj[name] = val
114
+    }
115
+  })
116
+  return obj
115 117
 }

+ 21 - 0
tests/unit/utils/param2Obj.spec.js

@@ -0,0 +1,21 @@
1
+/**
2
+ * @param {string} url
3
+ * @returns {Object}
4
+ */
5
+export function param2Obj(url) {
6
+  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
7
+  if (!search) {
8
+    return {}
9
+  }
10
+  const obj = {}
11
+  const searchArr = search.split('&')
12
+  searchArr.forEach(v => {
13
+    const index = v.indexOf('=')
14
+    if (index !== -1) {
15
+      const name = v.substring(0, index)
16
+      const val = v.substring(index + 1, v.length)
17
+      obj[name] = val
18
+    }
19
+  })
20
+  return obj
21
+}