问题背景

在node v13.5.0中通过url模块解析get请求参数的时候,遇到query: [Object: null prototype]

var  url  =  require("url");
var  params  =  url.parse("/?name=hello&&age=12", true);

console.log(params);

//  query: [Object: null prototype] { name: 'hello', age: '12' }

如果我们在nodeconsole.log一个null prototype,就会出现[Object: null prototype]

const obj1 = Object.create(null);
obj1['key'] = 'SomeValue' ;
console.log(obj1); 
// [Object: null prototype] { 'key' : 'SomeValue' }

const obj2 = {};
obj2['key'] = 'SomeValue' ;
console.log(obj2); 
// { 'key' : 'SomeValue' } 

而上面会出现这个问题的原因也许跟解析url的库有关,url.parse(req.url, false / true ) ,设置true时URL encoded 使用qs,设置false时 , 使用query-string,参考stackoverflow

解决方法

解决这个问题,可以通过JSON.stringify()JSON.parse()

var url = require("url");

var params = JSON.stringify(url.parse("/?name=hello&&age=12", true).query);
console.log(JSON.parse(params));

// { name: 'hello', age: '12' }

WHATWG URL API

url 模块用于处理与解析 URL。url 模块提供了两套 API 来处理 URL:一个是旧版本遗留的 API,一个是实现了 WHATWG标准的新 API。

在node 7.0以后,已经支持WHATWG URL API,了解更多

var url = require("url");
var params = new URL("/?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:',
  username: '',
  password: '',
  host: 'localhost:8888',
  hostname: 'localhost',
  port: '8888',
  pathname: '/',
  search: '?name=hello&&age=12',
  searchParams: URLSearchParams { 'name' => 'hello', 'age' => '12' },
  hash: ''
}

console.log(params.searchParams.get("name")); // hello

dragonishare
157 声望3 粉丝