Express JS #4 - Query Parameters

Anson the Developer
9 Feb 202412:52

Summary

TLDRThis video script explains the use of query strings and parameters in backend development. It covers how they appear in a URL, their role in sending data across pages, and manipulating server-side data retrieval. The tutorial demonstrates filtering and sorting user data based on query parameters, using JavaScript's array filter method. It also shows how to handle cases where query parameters are incomplete.

Takeaways

  • 🔍 Query strings are used to send data at the end of a URL, following a '?' symbol.
  • 🔑 Query parameters are key-value pairs that can be added after the '?' in a URL, separated by '&'.
  • 🌐 They are commonly used in web development to pass data between pages or to add additional data to HTTP requests.
  • 📄 The query string is parsed into a JSON object by Express, making it easy to access the values.
  • 🔄 Query parameters can be used to sort or filter data on the server side before sending it back to the client.
  • 📝 In a GET request, query parameters are used to specify how data should be manipulated or filtered without altering the data itself on the server.
  • 🛠️ Developers can use query parameters to implement features like searching or filtering within arrays of data, such as user objects.
  • 📊 Filtering can be done based on substrings within specific fields of an object, like 'username' or 'display name'.
  • 📈 The script demonstrates how to handle query parameters in a Node.js/Express application, including checking for their existence and applying filters.
  • 💻 It's important to ensure that both the filter type and value are provided in the query parameters for the filtering to work correctly.

Q & A

  • What is a query string?

    -A query string is a part of a URL that appears after a question mark (?) and contains key-value pairs that are used to send data to a web server.

  • How are query parameters used in backend development?

    -Query parameters are used in backend development to send data from the client to the server, filter and sort data, and manipulate data retrieval from databases based on specific criteria.

  • What is the purpose of the equals sign '=' in a query string?

    -The equals sign '=' in a query string is used to assign a value to a key, similar to assigning a value to a variable, but in the context of a URL.

  • How can you pass multiple key-value pairs in a query string?

    -Multiple key-value pairs in a query string can be passed by separating each pair with an ampersand (&) symbol.

  • How does a query string differ from a request body?

    -A query string is part of the URL and is used to send data to the server without changing the state of the server, while a request body is used in POST requests to send data to the server that may change its state.

  • What is the role of the request.query object in Express.js?

    -The request.query object in Express.js is used to access the query parameters sent in the query string of the URL.

  • Can you provide an example of how to filter an array based on a query parameter in Express.js?

    -Yes, you can filter an array based on a query parameter by accessing the request.query object, destructuring the specific query parameter, and using it as a condition in the array's filter method.

  • What is the significance of the includes method in filtering query parameters?

    -The includes method is used to check if a string contains a specific substring, which is useful for filtering data based on partial matches of strings in query parameters.

  • How do you handle cases where only one of the query parameters (filter or value) is provided?

    -You should handle cases where only one query parameter is provided by checking if both parameters exist and, if not, returning the original data without applying any filters.

  • What is the purpose of the filter function in JavaScript when dealing with query parameters?

    -The filter function in JavaScript is used to create a new array with all elements that pass the test implemented by the provided function, which can be used to filter data based on query parameters.

  • How can query parameters be used to sort data retrieved from a server?

    -Query parameters can be used to specify sorting criteria such as sorting by a specific field or in a specific order, which the server can then use to sort the data before sending it back to the client.

Outlines

00:00

🌐 Understanding Query Strings and Parameters

The speaker introduces query strings and parameters, explaining how they appear at the end of a URL in a web browser. They describe the structure, which includes a question mark followed by key-value pairs separated by an ampersand. Query strings are used to pass data in backend development and can be sent from one page to another or to add additional data to a server-side request. The speaker uses an example to show how query strings can be used to manipulate data, such as sorting or filtering a list of users based on specific criteria before it is returned from the server.

05:00

🔍 Implementing Query String Filtering

The speaker elaborates on how to use query parameters for filtering data. They demonstrate setting up a route handler that expects two query parameters: 'filter' to specify the field to filter by (either 'username' or 'display name'), and 'value' for the substring to match within that field. The speaker shows how to destructure these parameters from the request object and implement a filter function that checks if the specified field in user objects contains the given substring. If both parameters are provided, the function filters the user array accordingly; otherwise, it returns the unfiltered array.

10:01

📝 Testing Query String Functionality

The speaker tests the functionality of the query string filtering by making GET requests with different query parameters. They show that without any parameters, the full user array is returned. When providing only the 'filter' parameter without a corresponding 'value', no data is returned as the request is pending. However, when both 'filter' and 'value' parameters are included, the server correctly filters the user data based on the criteria. The speaker also discusses handling cases where only one parameter is provided, ensuring that the server does not perform any filtering in such scenarios and returns the full user array.

Mindmap

Keywords

💡Query Strings

Query strings are a part of a URL that appear after a question mark (?) and contain key-value pairs. They are used to send data to a web server without changing the page or resource being requested. In the video, query strings are used to pass parameters to backend servers, allowing for dynamic data retrieval based on user input or application state.

💡Query Parameters

Query parameters are the individual key-value pairs found within a query string. They are used to send additional data to the server. In the script, the speaker discusses how query parameters can be used to filter and sort data retrieved from a backend, such as sorting users by username or filtering users by a specific substring in their username.

💡Backend Development

Backend development refers to the server-side of software development, where the primary focus is on the server, database, and application logic. The video script discusses backend development in the context of handling query strings and parameters to manipulate data before sending it to the client.

💡URL

A URL (Uniform Resource Locator) is a reference to a web resource that specifies its location on a computer network and a mechanism for retrieving it. The script mentions URLs in the context of where query strings are located, specifically at the end of the URL after the domain and route.

💡Key-Value Pairs

Key-value pairs are a fundamental data structure used to store data. In the context of the video, key-value pairs are used within query strings to send data to the server, where the key is the parameter name and the value is the data associated with that parameter.

💡HTTP Request

An HTTP request is a message sent from a client to a server to request access to a resource. The video discusses GET requests, which are a type of HTTP request used to retrieve data from a specified resource, often utilizing query parameters to define the data to be retrieved.

💡Request Object

In web development, the request object is a structure that contains all the information about an incoming HTTP request. The script explains how the request object in a Node.js/Express application contains properties like query parameters, which can be accessed to handle data sent by the client.

💡Filtering

Filtering is the process of selecting a subset of items from a larger set based on certain criteria. The video script describes how to use query parameters to filter data on the server side, such as returning only users whose usernames contain a certain substring.

💡Sorting

Sorting is the process of arranging data in a specific order. The script provides an example of how query parameters can be used to sort user data, such as sorting an array of user objects alphabetically by username or by ID in ascending order.

💡Substring

A substring is a contiguous sequence of characters within a string. In the context of the video, substrings are used in query parameters to filter data, such as retrieving users whose usernames contain a specific substring.

💡Mock Data

Mock data is fictional data used for testing purposes. In the script, mock data represents user objects that might be retrieved from a database, and it is used to demonstrate how query parameters can be used to filter and sort this data.

Highlights

Introduction to query strings and parameters in backend development.

Explanation of query strings appearing at the end of a URL.

Description of how to use key-value pairs in query strings.

Use of the ampersand (&) as a delimiter for multiple query parameters.

Query parameters used for sending data across pages in web development.

Sending query parameters from client-side to server-side to add additional data to requests.

Example of using query strings to manipulate data retrieval on the server-side.

Demonstration of sorting users array based on alphabetical order using query parameters.

Explanation of filtering users based on a substring in their username.

Guide on how to send query strings to a server.

Console logging of the request.query object to access query parameters.

Building a realistic filter function to handle query parameters for user data.

Destructuring the query object to access specific query parameters.

Implementation of a filter function to return user objects based on substring matches.

Testing the filter functionality with different query parameters.

Handling cases where query parameters are incomplete or undefined.

Ensuring that both filter and value query parameters are defined for proper filtering.

Finalizing the implementation by handling all cases of query parameter presence or absence.

Transcripts

play00:03

so now I'm going to go ahead and talk

play00:04

about query strings and query parameters

play00:07

and how they are used in backend

play00:09

development and how we can actually use

play00:11

them ourselves so many of you may have

play00:14

seen something at the end of the website

play00:18

address so in the browser uh address URL

play00:21

you might see this question mark and

play00:24

then you might see something like key

play00:26

equals value and then you might see an

play00:29

ENT symbol and you might see another key

play00:32

equals value this is known as a query

play00:35

string so right over here this question

play00:38

mark symbol denotes that we have a query

play00:40

string and they go at the end of our uh

play00:44

defined route over here okay so you have

play00:46

the domain and then the route the path

play00:50

and then the query string at the end and

play00:53

then after the question mark you

play00:54

basically just pass in whatever key

play00:57

value pairs you want so for example I

play00:59

have uh a key called key and I use the

play01:02

equals operator to assign a value to it

play01:06

so it's kind of like assigning a value

play01:08

to a variable but only we're doing it in

play01:09

the address bar so key equals value and

play01:12

if I wanted more query parameters in the

play01:15

query string I can just simply use this

play01:17

ENT as a delim so ENT and then the next

play01:21

key value pair so key2 equals value to I

play01:24

can have as many query parameters as I

play01:27

want now there are different ways that

play01:28

you can use Query parameters in web

play01:30

development you can send query

play01:33

parameters from a page to another page

play01:35

on the client side so that way you can

play01:38

send data uh across different pages so

play01:41

let's say if one page needs data from

play01:43

another page when you're navigating then

play01:46

you can grab the values from the query

play01:48

query string if you're sending it from

play01:50

the client side to the server side

play01:52

typically you would send a query string

play01:54

to uh add additional data to the request

play01:58

that you normally wouldn't add in a a

play02:00

request body we haven't gone to post

play02:02

requests just yet but I'll stick to a

play02:04

get request as an example so when you

play02:07

make a get request remember that you are

play02:09

performing a request an HTTP request to

play02:12

get data in readon format you're not

play02:14

manipulating any data at all on the

play02:17

server side so sometimes you might need

play02:20

to retrieve the data but you also want

play02:22

to have that data already um manipulated

play02:25

in a certain way on the server side so

play02:27

for example up top over here I added a

play02:30

couple more user objects so let's say I

play02:33

have this users array and let's pretend

play02:35

it's from the database and let's say I

play02:37

want all of these users returned back

play02:39

but I wanted it sorted in alphabetical

play02:42

order based on the username or you can

play02:44

also have it sorted based on the display

play02:46

name maybe you might also want it sorted

play02:48

in um from least to greatest based on

play02:50

the ID value since these IDs are

play02:53

integers so you would use a query string

play02:55

to do that let's say if you also wanted

play02:58

to filter out some some results from the

play03:01

users itself maybe you don't want to get

play03:04

every single user from the database you

play03:06

only want to get only specific users

play03:09

that match where their username matches

play03:11

a substring so maybe I only want to get

play03:15

all the users that have an A in their

play03:19

username field so hopefully that makes

play03:21

sense with query parameters and how they

play03:23

can be used so let's go ahead and see

play03:27

how we can actually send query strings

play03:29

and query parameters to our server so

play03:33

inside my/ API users route inside the

play03:37

request Handler function I'm going to go

play03:40

ahead and conso log this request. query

play03:43

object remember how I said earlier the

play03:45

request object has everything that you

play03:47

can possibly get in regards to the

play03:49

request itself so earlier we referenced

play03:52

request. prams to get the route

play03:55

parameter so to get the query parameters

play03:57

from the query string we just ref

play03:59

reference request. query so let's go

play04:01

ahead and send a query string when we

play04:04

are making this request to the/ users

play04:07

and point so I'm going to use the

play04:09

question mark symbol and then provide

play04:12

some key value pairs I can literally

play04:14

pass any key value pair I want so let's

play04:16

do something like filter and we'll

play04:18

assume the filter is going to be based

play04:19

on username um so I'll do filter uh

play04:23

Anson and I'll go into my console uh let

play04:26

me actually just rerun the request so

play04:29

you see how whenever I send a request a

play04:32

get request to that endpoint in the

play04:34

console it logs that request query

play04:37

object and it has the filter which is

play04:39

the key that I passed in the query

play04:41

parameter filter it is showing up as a

play04:44

field in that object that query object

play04:48

and we have the uh string Anon as the

play04:50

value so the query string gets parsed

play04:53

into a Json object by Express so we can

play04:56

very easily grab the values let's go

play04:58

ahead and actually do something

play05:00

realistic with the filtering so what

play05:01

I'll do is this I want to make it so

play05:04

that I can filter based on sub some

play05:06

substring so I want to go ahead and also

play05:08

make it so that I can also set which

play05:10

field in this mock users array in in

play05:13

these objects I want to make sure I can

play05:14

set which field I want to filter on so

play05:16

maybe I want to alternate between

play05:17

filtering by username or display name so

play05:21

for the filter value we can expect it to

play05:24

only be two possible values

play05:26

username or display name and this will

play05:29

tell us what uh key in the user object

play05:34

what field to filter by or yeah what

play05:36

what field to filter and then we will

play05:38

add an additional query parameter you

play05:40

can call it whatever you want but I

play05:41

guess we can call it a value just to

play05:44

keep things simple and then this value

play05:47

will basically be the uh the text the

play05:50

substring that you want to have that

play05:52

username contain so if I want to filter

play05:55

everything where it contains the an

play05:57

substring so a an substring then we

play05:59

would have to search for that okay so

play06:02

I'm going to send these two query

play06:05

parameters to the server okay so now I'm

play06:08

going to go

play06:10

into go back to the request Handler for

play06:13

the users endpoint and what I'll do is

play06:15

this I'm going to

play06:17

destructure that query object from the

play06:20

request object and then I also want to

play06:22

destructure from the query

play06:25

object the two query parameters filter

play06:28

and value and I can do that all in one

play06:32

go like this so I can use so after query

play06:35

I can additionally destructure

play06:37

properties from query so let's do filter

play06:40

and value and so what I want to do is I

play06:44

want to make sure that both of these

play06:45

query parameters exist because of course

play06:48

if they don't exist then we're not going

play06:50

to do any filtering at all so the

play06:53

easiest case that we can handle is we

play06:55

check to see if both of these values are

play06:57

undefined because if they are then we

play06:59

don't need to do any filtering we just

play07:01

return mock users as is so we'll you

play07:05

write an if case if there's no filter

play07:08

and there's no value then we will just

play07:11

simply return response. send and then

play07:15

call or not not call uh pass and mock

play07:17

users in this do send method call okay

play07:20

that's the easiest case I'll write a

play07:22

simple comment when filter and and value

play07:26

are

play07:28

undefined

play07:31

okay and we always want to make sure

play07:34

that both of these query parameters are

play07:36

defined because you need both of them of

play07:38

course you can't have a value and not

play07:40

know what field in the user object you

play07:43

want to filter by and if you have the

play07:45

filter query parameter defined you need

play07:47

to make sure you have an actual text

play07:49

that you want to filter uh that you want

play07:52

to filter based on so we need to make

play07:54

sure that both of these are defined so

play07:56

we'll do if filter and

play08:00

value if filter n value we will

play08:06

return and we'll call response. send and

play08:09

from here I should just be able to write

play08:12

a simple filter function so mock users I

play08:16

can use the filter function on the array

play08:19

and pass in a predicate so what we're

play08:22

going to do is we're going to pass in

play08:23

this callback function also known as a

play08:24

predicate function and this will this

play08:27

callback function has uh the user as an

play08:31

argument and then what we want to do is

play08:34

we want to filter out all of the we want

play08:37

to filter all the user objects that

play08:39

match that have that value as a

play08:41

substring so it's pretty easy we can do

play08:43

user. username cuz remember we're

play08:46

filtering by by the

play08:48

username or actually it would be user

play08:52

square brackets filter okay and this is

play08:55

assuming that filter would either be

play08:57

display name or username

play08:59

so user filter so this would grab the

play09:02

correct field and then we would want to

play09:05

so this is a this is going to be a

play09:06

string so we would want to make sure we

play09:09

check to see if the string

play09:11

contains that substring so we actually

play09:14

have this um

play09:18

includes and this method returns true if

play09:21

search string appears as a substring of

play09:22

the result of converting this object to

play09:24

a string okay so I can pretty much call

play09:29

do

play09:30

includes and I'll pass in the value so

play09:34

this will filter all of this will

play09:36

basically grab all of the user objects

play09:39

that pass this predicate so if the user

play09:42

and whether we are filtering by username

play09:44

or display name if let's say for example

play09:46

let's stick with username if the

play09:48

username includes the value that we're

play09:50

trying to filter then it's going to

play09:53

return that into a new array and then

play09:57

once all of the filtering is done we're

play09:58

going to send the the entirey back so

play10:00

let's go ahead and test this out so

play10:02

right now if I let's do this if I don't

play10:05

have any of the query parameters at all

play10:08

you can see that it will just return the

play10:10

array as is okay it doesn't uh it

play10:13

doesn't do anything wa everything's

play10:15

sorted we have everything the way it is

play10:17

nothing is sorted nothing is done let's

play10:20

go ahead and add a filter so filter

play10:23

let's filter by

play10:25

username and now notice how if I were to

play10:29

only have the filter but no value you'll

play10:34

see how it doesn't return anything yet

play10:36

the request is still pending that's

play10:38

because we need both filter and value

play10:41

okay we'll handle these cases as well so

play10:44

let's go ahead and handle the case where

play10:46

we have both filter and value as a query

play10:49

parameter so for the value query

play10:51

parameter I will set this to be a n and

play10:55

now you'll see this will grab me all of

play10:58

the user objects where the username has

play11:02

a n as a substring and if you look right

play11:05

over here it seems to be filtering

play11:08

correctly uh I can go ahead and do

play11:10

another simple case where let's

play11:13

filter the username where it includes e

play11:16

as a substring and you can see that

play11:18

seems like the only username that I have

play11:22

that has an e as a substring is

play11:24

Henry okay uh let's see what else let's

play11:27

try

play11:29

um let's try

play11:32

a I have 1 2 3 4 5 so it's missing uh

play11:38

this object Henry so our filtering is

play11:40

working great okay so let's just finish

play11:43

this out um so let's make sure we handle

play11:47

all the other cases where if we don't

play11:49

have both of

play11:51

these um both of these defined then we

play11:56

return the same mock users that is in

play12:00

memory so we don't do any filtering at

play12:01

all so I think the easy thing to do is

play12:04

actually this instead of uh doing this

play12:06

if check right up here where we check

play12:08

both a filter and where we check if

play12:11

there's no filter and there's no value

play12:13

what we'll do is we'll check if there's

play12:15

a filter and if there's a value and if

play12:19

this condition fails and that means it

play12:21

only has one or the other defined or

play12:25

both are undefined so then we'll just

play12:27

return response. send

play12:29

mock users so I just realized that I'm

play12:31

going to fix that real quick and now

play12:33

when I go back to the browser if I only

play12:35

have one query parameter it won't do any

play12:39

filtering at

play12:40

all okay hopefully this makes

play12:50

sense

Rate This

5.0 / 5 (0 votes)

関連タグ
Backend DevelopmentQuery StringsWeb DevelopmentAPI UsageData FilteringHTTP RequestsGET RequestsData RetrievalExpress.jsJavaScript
英語で要約が必要ですか?