當咱們用get方法提交表單時,在url上會顯示出請求的參數組成的字符串,例如:http://localhost:3000/index.html?phone=12345678901&pwd=123123,在服務器端咱們要獲取其中的參數來進行操做,這種狀況下,就要對請求過來的網址進行拆解了。下面將用3種方法實現:html
一、js原生方法node
思路:先經過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);
二、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指向了 請求參數的字符串部分。ui
三、node.js方法之url的解構方法url
思路:使用node.js自帶的URL構造函數獲得。spa
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()));