1

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'
}

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow thank you very much now I understood it :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.