[javascript] Parsing Query String in node.js

In this "Hello World" example:

// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

How can I get the parameters from the query string?

http://127.0.0.1:8000/status?name=ryan

In the documentation, they mentioned:

node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan'
, search: '?name=ryan'
, query: { name: 'ryan' }
, pathname: '/status'
}

But I did not understand how to use it. Could anyone explain?

This question is related to javascript http node.js

The answer is


Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:

// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');

// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';

// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
  // Parse the request URL. Relative URLs require an origin explicitly.
  const url = new URL(request.url, serverOrigin);
  // Parse the URL query. The leading '?' has to be removed before this.
  const query = parseQuery(url.search.substr(1));
  response.writeHead(200, { 'Content-Type': 'text/plain' });
  response.end(`Hello, ${query.name}!\n`);
});

// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);

// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);

If you run the script above, you can test the server response like this, for example:

curl -q http://localhost:8000/status?name=ryan
Hello, ryan!

There's also the QueryString module's parse() method:

var http = require('http'),
    queryString = require('querystring');

http.createServer(function (oRequest, oResponse) {

    var oQueryParams;

    // get query params as object
    if (oRequest.url.indexOf('?') >= 0) {
        oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));

        // do stuff
        console.log(oQueryParams);
    }

    oResponse.writeHead(200, {'Content-Type': 'text/plain'});
    oResponse.end('Hello world.');

}).listen(1337, '127.0.0.1');

require('url').parse('/status?name=ryan', {parseQueryString: true}).query

returns

{ name: 'ryan' }

ref: https://nodejs.org/api/url.html#url_urlobject_query


node -v v9.10.1

If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

So I would suggest use JSON.stringify

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`