Previous Lecture Complete and continue  

  What's in Query

Okay, we're moving to the next adventure. I'll promise you, it will be very easy. So if you look at the problem, we have this string. It's called query string. This is another way to pass the information from browser to the server, and it's similar to URL parameter, but it's not quite the same, because you get the data after this question mark, so it's called a query string. So what we need to do, we need to implement a faster search. Query strings are often used in searches to provide some filters, for example, or some options, and we would use GET for that, okay? So let's go to our editor. And I'm creating another file. This is adventure number seven. So the good thing about query similar to the param middle, where we don't need any external modules. It will just work automatically.

We don't need to apply anything, as well. So we're importing the express module, creating an object, and then we define our browse/search, get/search, and we have the request handler with And then the query object is basically inside of the request object, req.query. That's our guy. And then we output it back, and then we, on line nine, we're listening to the port provided to us by the workshop. As always, we can create a manual fallback hard-coded value of 3000, in case we want to launch it without any arguments. So you can have multiple objects here. So Express.js will automatically create that object for you, and populate it. Okay, so let's Save it. Let's go to the Terminal. The terminal, I want to run this. It's actually number seven. Okay, so it works, and that's wonderful. Okay, it passes. Our solution is similar to the official solution. No longer there. But let me demo you how it works, and how it looks in the browser. We haven't done that for awhile. So, here I am. This is left over from some previous exercises. So let's say name is John, and age is 30. It crashes, because I don't have it running, so it's always a good thing to have the server running before testing it.

Okay, so now I'm running it, refresh and I get my object back. The reason why you see this nicely formatted, I'm using this Chrome extension, it's called JSONView, so you would see something like that, because most likely you don't have that extension yet, but it's a good extension, go get it. And yeah, we can have multiple parameters. So the interesting thing with Express.js is, if we have two parameters in a query string with the same T, with the same name basically different values, in this case 30 and 31, Express.js will work just fine. It will create an array of values, so just be mindful when you're checking for existence, when it's sanitizing your data input, don't introduce any vulnerabilities, security vulnerabilities for hackers, because yeah, the data that will change from a string, now it's an array, and both strings and array, in JavaScript if you use that length that would work. So that's all.

0 comments