问题背景在nodev13.5.0中通过url模块解析get请求参数时遇到query:[Object:nullprototype]varurl=require("url");varparams=url.parse("/?name=hello&&age=12",true);console.log(params);//query:[Object:nullprototype]{name:'hello',age:'12'}如果我们在节点中console.log一个空原型,[Object:nullprototype]constobj1=Object.create(null);obj1['key']='SomeValue';console.log(obj1);//[Object:nullprototype]{'key':'SomeValue'}constobj2={};obj2['key']='SomeValue';console.log(obj2);//{'key':'SomeValue'}出现上述问题的原因可能与解析url的库url.parse(req.url,false/true)有关,设置为true时,URL编码使用qs,设置false时使用query-string,参考stackoverflow的解决办法,可以通过JSON.stringify()和JSON.parse()varurl=require("url");varparams=JSON.stringify(url.parse("/?name=hello&&age=12",true).query);console.log(JSON.parse(params));//{name:'hello',age:'12'}WHATWGURLAPIurl模块用于处理和解决url模块提供了两套处理URL的API:一套是老版本的legacyAPI,一套是实现WHATWG标准的新API。node7.0之后,已经支持WHATWGURLAPI,了解更多varurl=require("url");varparams=newURL("/?name=hello&&age=12","http://localhost:8888/");console.log(params);//输出结果URL{href:'http://localhost:8888/?name=hello&&age=12',origin:'http://localhost:8888',protocol:'http:',用户名:'',密码:'',主机:'localhost:8888',主机名:'localhost',端口:'8888',路径名:'/',搜索:'?name=hello&&age=12',searchParams:URLSearchParams{'name'=>'hello','age'=>'12'},hash:''}console.log(params.searchParams.get("name"));//你好
