當我們用get方法提交表單時,在url上會顯示出請求的參數組成的字符串,例如:http://localhost:3000/index.html?phone=12345678901&pwd=123123,在服務器端我們要獲取其中的參數來進行操作,這種情況下,就要對請求過來的網址進行拆解了。下面將用3種方法實現:
1、js原生方法
思路:先通過split拆解?得到字符串phone=12345678901&pwd=123123 ,然后在通過split拆解&符號左右的字符串,最后再通過split拆解=號左右的字符串即可。
let str = "http://localhost:3000/index.html?phone=12345678901&pwd=123123"; let arr = str.split("?")[1].split("&"); //先通過?分解得到?后面的所需字符串,再將其通過&分解開存放在數組里 let obj = {}; for (let i of arr) { obj[i.split("=")[0]] = i.split("=")[1]; //對數組每項用=分解開,=前為對象屬性名,=后為屬性值 } console.log(obj);
2、node.js方法之url+queryString
思路:先通過url.parse(str1)獲得一個分解url的對象,調用query屬性得到字符串:phone=12345678901&pwd=123123 ;然后用querystring.parse()方法來直接轉換成JSON對象。
const url = require("url"); const querystring = require("querystring"); let str1 = "http://localhost:3000/index.html?phone=12345678901&pwd=123123"; console.log(querystring.parse(url.parse(str1).query));
url.parse()轉化分解后的url對象來源:可見query指向了 請求參數的字符串部分。
3、node.js方法之url的解構方法
思路:使用node.js自帶的URL構造函數得到。
const {URL} = require("url");
let str1 = "http://localhost:3000/index.html?phone=12345678901&pwd=123123";
let obj1 = new URL(str);
console.log(querystring.parse(obj1.searchParams.toString()));