首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >什么是查询:[Object: null prototype]在url.parse()中使用nodeJS

问什么是查询:[Object: null prototype]在url.parse()中使用nodeJS
EN

Stack Overflow用户
提问于 2021-04-30 03:53:21
回答 1查看 752关注 0票数 1

我现在已经开始为我的项目学习nodeJS,并且仍然在适应nodeJS的方式。我的问题是,当我访问.query方法时访问url.parse(request.url,true)时,查询: Object: null原型意味着什么?我有点糊涂。我只是想尝试一下我正在看的视频教程,但是因为我有一个错误而无法赶上它。谢谢你的帮助。

这是我的密码

代码语言:javascript
复制
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中输出

代码语言:javascript
复制
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'
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-30 08:05:37

这意味着query属性指向具有null原型的对象。Prototype是javascript用于继承的机制--实际上是属性访问委托。因此,在这里,query对象不继承任何属性,特别是不能访问定义在Object.prototype上的基线对象方法。

通过控制台记录带有null原型的空白对象,您将获得类似的输出:

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67327969

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档