我现在已经开始为我的项目学习nodeJS,并且仍然在适应nodeJS的方式。我的问题是,当我访问.query方法时访问url.parse(request.url,true)时,查询: Object: null原型意味着什么?我有点糊涂。我只是想尝试一下我正在看的视频教程,但是因为我有一个错误而无法赶上它。谢谢你的帮助。
这是我的密码
const http = require('http');
const url = require('url');
const port = 8080;
const server = http.createServer();
server.on('request', (request, response) => {
const urlParsed = url.parse(request.url, true);
console.log(urlParsed);
if (request.method === 'GET' && request.pathname === '/metadata') {
const { id } = urlParsed.query;
console.log(id) <<<<<<<<<<<<<<<< I cannot output this in the CLI
}
});
server.listen(port, () => {
console.log(`Server is listening to localhost:${ port }`)
});然后是curl http://localhost:8080/metadata/?id=1
然后在CLI中输出
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?id=1',
query: [Object: null prototype] { id: '1' },
pathname: '/metadata/',
path: '/metadata/?id=1',
href: '/metadata/?id=1'
}发布于 2021-04-30 08:05:37
这意味着query属性指向具有null原型的对象。Prototype是javascript用于继承的机制--实际上是属性访问委托。因此,在这里,query对象不继承任何属性,特别是不能访问定义在Object.prototype上的基线对象方法。
通过控制台记录带有null原型的空白对象,您将获得类似的输出:
var object = Object.create(null)
console.log(object)
// output: [Object: null prototype] {}当parseQueryString参数( url.parse()的第二个参数)为真时,通过调用querystring模块parse()方法获得查询对象。文档实际上指定了有关此方法的以下内容:
querystring.parse()方法返回的对象不典型地从JavaScript Object__继承。
https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options
https://stackoverflow.com/questions/67327969
复制相似问题