ERROR 401
ERROR 401

Reputation: 129

What is query: [Object: null prototype] in url.parse() using nodeJS

I am starting to learn nodeJS for my project right now and still adapting the way of nodeJS. My question is what does it mean by query: [Object: null prototype] when I accessed the .query method when accessing url.parse(request.url, true)? I am a little bit confused. I just want to try the video tutorial that I am watching but can't catch up because I have an error. Thank you for the help.

Here is my code

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 }`)
});

then curl http://localhost:8080/metadata/?id=1

Then output in 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'
}

Upvotes: 1

Views: 1616

Answers (1)

IAmDranged
IAmDranged

Reputation: 3020

This means that the query property points to an object with a null prototype. Prototype is the mechanism used by javascript for inheritance - actually property access delegation. So here the query object doesn't inherit any properties - and in particular doesn't have access to baseline object methods defined on Object.prototype.

You would get a similar output by console logging a blank object with a null prototype:

var object = Object.create(null)
console.log(object)

// output: [Object: null prototype] {}

When the parseQueryString parameter - the second one - of url.parse() is true, the query object is obtained by calling the querystring module parse() method. The documentation actually specifies this about this method:

The object returned by the querystring.parse() method does not prototypically inherit from the JavaScript Object.

https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options

Upvotes: 2

Related Questions