The node.js query string module.
When making a node.js project there might come a need to do something involving working with a query string, that is the parameters that are defined in a url using question marks, equal sign, and ampersands. It is a standard way of communicating some parameters to a server by way of a url, rather than some other means such as a post request payload.
I could work out some javaScript to help with parsing a query string to an object, and vice versa, but why bother with that when there is a built in module in node.js to do this called the querystring module.
Basic example of query string parse method.
The main method of interest is the parse method, this is what can be used to quickly parse a url parameter query string into a javaScript object that can be worked with in a project. To use it just grab a reference to what is exported using require, and give the string to parse to the parse method.
|
|
Make sure the question mark is not in the string.
With query strings the question mark is used to denote that the path of a resource has ended, and a query string has started. When passing a query string to the parse method, the question mark should be omitted, or else it will be the first character of the key of the first value in the query string.
So something needs to be done to make sure that does not happen, as it seems that the parse method will not do any of that kind of sanitation for you.
|
|
When working with a full url the query string needs to be extracted.
A quick and simple way to do it is to just use String.split.
|
|
Making a simple method to work with most situations
You might feel compelled to make a method to help assure that most typically query string scenarios are handled in a way that will always result in a clean, and sane object of key value pares. Making something that will work for most typical scenarios is not to hard.
|
|
A word on security
Like that of post requests a query string can be the result of your own client system, but the client system can also be bypassed. In other words a query string is a potential entry point with respect to a certain type of hacking. I have not taken the time to work out an actual example, but for now I will just say that it is important to be aware of how the object that is parsed from the query string is being used.