url地址数据参数转化JSON对象(js三种方法实现)

当我们用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()));

猜你喜欢

转载自www.cnblogs.com/zhangzhiyong/p/9949641.html
今日推荐